Michael D Johnson
Michael D Johnson

Reputation: 929

Render Grails template from external source

We have a gsp that's stored on S3 to allow realtime updates. The file has to remain on S3. I'm retrieving the file and using the Grails templating engine to render it. However, when calling this code from a Quartz job I get the 'request not attached' error because a Job is not executed within a request context.

I was reading that I should use PageRenderer, which is included in Grails 2.x+. However, PageRenderer only seems to support reading a template from a relative path (i.e. it expects you to have it locally). Can someone educate me on a way to render a template using PageRenderer not from a file, but from a String? I've also already tried using a url as the template path, but no luck there.

Ideas?

Upvotes: 2

Views: 756

Answers (2)

Michael D Johnson
Michael D Johnson

Reputation: 929

So the answer to this is fairly trivial, although it required a fair amount of research on my part. If your using groovyPagesTemplateEngine outside of a request context (i.e. jobs) than you have to mock the request context within the method your calling template.make(). You use to have to write some code and include Spring dependencies to make this happen but now Grails has a nifty little utility that you can use. Just include GrailsWebUtil.bindMockWebRequest() before you make your template call and you should be fine.

Upvotes: 2

user800014
user800014

Reputation:

Looking at this thread it seems that you can transform a String in a template using groovyPagesTemplateEngine. Example:

// compile the gsp
def compiledContent = groovyPagesTemplateEngine.createTemplate(content, 'SomeUniqueIdForTheContentBeingRendered')

// render the gsp
def sw = new StringWriter()
compiledContent?.make(args)?.writeTo(sw)
String renderedContent = sw.toString()

Upvotes: 0

Related Questions