Search

Dark theme | Light theme

February 19, 2011

Grails Goodness: Templates Can Have a Body

To create a more modular Groovy Server Page we can use Grails' template support. We use <g:render template="..." ... /> or <tmpl:templateName ... /> tags to render the template content. These tags can have a body. The body of the tag is then available in the template code. We use the expression ${body()} in our template to output the body content.

Suppose we have the following template code:

<%-- File: grails-app/views/product/_productView.gsp --%>
<h2>${product.name}</h2>

${body()}

We can use the template with different body contents:

...
<g:each in="${products}" var="product">
    <g:render template="productView" model="[product: product]">
        <g:link uri="/">Back to home</g:link>
    </g:render>
</g:each>
...
<g:each in="${products}" var="product">
    <tmpl:productView product="${product}">
        <g:link controller="product" action="details" id="${product.id}">More details</g:link>
    </tmpl:productView>
</g:each>
...

If the content of the body has HTML tags and we have set in grails-app/conf/Config.groovy the property grails.views.default.codec to html we get escaped HTML. Instead of using ${body()} we must then use <%= body() %>.