Search

Dark theme | Light theme

February 19, 2011

Grails Goodness: The Template Namespace

To have clean and re-usable Groovy Server Pages (GSP) we can use templates on our pages. A template contains HTML and code that we can maintain separately. In this post we learn about the template namespace to include a template on our page.

Suppose we have a page in our application that display a list of products. Each product has several properties we show. The template for a product is:

<%-- File: grails-app/views/product/_productView.gsp --%>
<li class="${cssClassName}">
    ${product.identifier}
    ${product.name}
    <g:formatNumber number="${product.price}" type="currency" currencyCode="EUR"/>
</li>

We can use the template with the g:render tag and template attribute on our page:

<%-- File: grails-app/views/product/list.gsp --%>
...
<ul>
    <g:render template="productView" 
              var="product" collection="${products}" 
              model="[cssClassName: 'info']"/>
</ul>
...
<ul>
    <g:each in="${products}" var="product">
        <g:render template="productView" model="[product: product, cssClassName: 'info']"/>
    </g:each>
</ul>
...

But we can also use the template namespace feature in Grails. We define a tag with the namespace tmpl and the tagname is our template name. We pass the model for the template through the attributes. Each attribute name/value pair is passed as model to the template.

<%-- File: grails-app/views/product/list.gsp --%>
...
<ul>
    <g:each in="${products}" var="product">
        <tmpl:productView product="${product}" cssClassName="info"/>
    </g:each>
</ul>
...