How to render a GSP in a Grails Service

You can render a model with a GSP template within a Grails service:

Given the following view:



You can create a service such as:

import grails.gsp.PageRenderer
import groovy.transform.CompileStatic

class GspRenderingService {
    PageRenderer groovyPageRenderer

    String render(String templatePath, Map<String, Object> model) {
        groovyPageRenderer.render(view: templatePath, model: model)

Which you can call from other Grails Artifacts:

[contact: new Contact(name: 'Sergio')])

@mrhaki has a more comprehensive blog post (Grails Goodness: Render GSP Views And Templates Outside Controllers) about this feature.

My next events:
🗓 May 27 09:00 AWS Dublin - Micronaut and AWS Lambda
🗓 Jul 20 09:00 Workshop Security in the Micronaut Framework
🗓 Sep 20 09:00 JCON Online 2022 - Getting Started with the Micronaut Framework
🗓 Sep 23 09:00 JCON Online 2022 - Micronaut® Framework and Microstream Java-native persistence engine

Tags: #grails #gsp
Sep 2021, 22.