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.

Tags: #grails #gsp
Sep 2021, 22.