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:

grails-app/views/contact/_contact.gsp

<h1>${contact.name}</h1>

You can create a service such as:


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

@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:

gspRenderingService.render('/contact/_contact',
[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