Loading...

May 6, 2010

Grails Goodness: Use the GSP Template Engine in a Controller

The GSP TemplateEngine used to render the GSP pages in Grails is also available as standalone service in for example our controllers, taglibs or services. In the Spring application context the template engine is loaded with the name groovyPagesTemplateEngine. This means we only have to define a new variable in our controller with this name and the Spring autowire by name functionality will automatically insert the template engine in our class. See the following code sample where we use the template engine, notice we even can use taglibs in our template code.

package com.mrhaki.grails

class SimpleController {
    def groovyPagesTemplateEngine
    
    def index = {
        def templateText = '''\
<html>
<body>
<h1>GSP Template Engine</h1>

<p>This is just a sample with template text.</p>

<g:if test="${show}"><p>We can use taglibs in our template!</p></g:if>

<ul>
<g:each in="${items}" var="item">
    <li>${item}</li>
</g:each>
</ul>
</body>
</html>
        '''
        
        def output = new StringWriter()
        groovyPagesTemplateEngine.createTemplate(templateText, 'sample').make([show: true, items: ['Grails','Groovy']]).writeTo(output)
        render output.toString()
    }
}

We get the following HTML output:

<html>
<body>
<h1>GSP Template Engine</h1>

<p>This is just a sample with template text.</p>

<p>We can use taglibs in our template!</p>

<ul>

    <li>Grails</li>

    <li>Groovy</li>

</ul>
</body>
</html>