20

Is it possible to "render" a template into a string? I would like to use a template and fill that with some values that I then must save to the local disc.

The render method always send the template to the client. I want something similar to run a template but save the output from the template to a local string variable that I can store in the local file system.

2 Answers 2

24

It is simpler than you think:

def myTemplateString = g.render(template: "test", model: [foo: bar])
3
  • This does nothing, why is it the accepted answer? What is the "g" variable?
    – Michael
    Jul 7, 2015 at 14:56
  • Also requires injecting the PageRenderer.
    – Michael
    Jul 7, 2015 at 15:11
  • 1
    @Michael, that depends on where you use it. In a service you need groovyPageRenderer, but in the controller you can use the render method that is also available in the GSP. So <g:render template="something" can be called like g.render(template: 'something').
    – Ivar
    Dec 23, 2015 at 11:15
14

If you are using Grails 2.x, you can use the PageRenderer class. Try something like this:

     grails.gsp.PageRenderer groovyPageRenderer

     void methodName() { 
         def contents = groovyPageRenderer.render(template:"yourTemplate", model:yourModel)
         //you can use contents as a string now
     }

This will work outside the scope of a web request as well, such as in a scheduled job or web service.

3
  • 2
    This does not work in Tomcat 6 for at least Grails version 2.1.1 and below. Mar 13, 2013 at 18:03
  • @JohnGiotta I believe you have to run in a container that supports Servlet 3.0 for this to work.
    – Ken Liu
    Jun 21, 2013 at 15:04
  • I'm running this from a service but I'm getting an extra slash in the urls for link and script tags generated by the Resources plugin, like this: "//static/...". Any ideas why?
    – rosenfeld
    Aug 6, 2013 at 12:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.