PJT PJT - 2 months ago 23
Groovy Question

How to use a gsp template to create a text file?

I have used the Grails Rendering Plugin in the past with much success in creating PDFs. Throw now I would like to create a simple text file, using a gsp. I loved the ease of using a model to define how to insert information into the template. I realize I don't need to render a text file, but is there a similar way to use a template to just create an ordinary text file?

Example from how to render a jpg using the Grails Render Plugin: (notice the model use)

def bytes = gifRenderingService.render(template: '/images/coupon', model: [serial: 12345])
// Render to a file
new File("coupon.jpg").withOutputStream { outputStream ->
jpegRenderingService.render(template: '/images/coupon', model: [serial: 12345])
}


If there isn't an easy way like the above example, since my information is coming from multiple domain classes should I just create
<g>
tags in my gsp template that pulls based on conditions needed? If that is the case.. how would I insert a variable into my gsp template from my service?

Answer

You might take a look at the grails.gsp.PageRenderer utility class. It allows you to render .gsp templates as a String:

String gspOutput = groovyPageRenderer.render(view: '<your view>.gsp', model: [ modelObj1: ... ])

... or directly to a Writer or OutputStream:

groovyPageRenderer.renderTo(view: '<your view>.gsp', model: [ modelObj1: ... ], <writer or OS>)

Much more detail can be found here: http://mrhaki.blogspot.com/2012/03/grails-goodness-render-gsp-views-and.html