Search code examples
grailsgroovygsp

GSP rendering programmatically


Suppose I have a gsp snippet stored in my database. How do I programmatically merge it with a data model to produce a string.


Solution

  • The applicationContext of any Grails app contains a bean named

    groovyPagesTemplateEngine
    

    By default this is a instance of GroovyPagesTemplateEngine. So you might use code like this in your controller or service:

    class MyService/MyController {
        def groovyPagesTemplateEngine
    
        String renderGSPToString(String uri, Map model) {
            groovyPagesTemplateEngine.createTemplate(uri).make(model).toString()
        }
    }
    

    NB: this snippet is not really taken from running code, it should just clarify the idea.