As well as views, Grails has the concept of templates. Templates are useful for separating out your views into maintainable chunks and combined with
Layouts provide a highly re-usable mechanism for structure views.
Template Basics
Grails uses the convention of placing an underscore before the name of a view to identify it as a template. For example a you may have a template that deals with rendering Books located at
grails-app/views/book/_bookTemplate.gsp
:
<div class="book" id="${book?.id}">
<div>Title: ${book?.title}</div>
<div>Author: ${book?.author?.name}</div>
</div>
To render this template from one of the views in
grails-app/views/book
you can use the
render tag:
<g:render template="bookTemplate" model="[book:myBook]" />
Notice how we pass into a model to use using the
model
attribute of the render tag. If you have multiple
Book
instances you can also render the template for each
Book
using the render tag:
<g:render template="bookTemplate" var="book" collection="${bookList}" />
Shared Templates
In the previous example we had a template that was specific to the
BookController
and its views at
grails-app/views/book
. However, you may want to share templates across your application.
In this case you can place them in the root views directory at grails-app/views or any subdirectory below that location and then with the template attribute use a
/
before the template name to indicate the relative template path. For example if you had a template called
grails-app/views/shared/_mySharedTemplate.gsp
, you could reference it as follows:
<g:render template="/shared/mySharedTemplate" />
You can also use this technique to reference templates in any directory from any view or controller:
<g:render template="/book/bookTemplate" model="[book:myBook]" />
The Template Namespace
Since templates are used so frequently there is template namespace, called
tmpl
, available that makes using templates easier. Consider for example the following usage pattern:
<g:render template="bookTemplate" model="[book:myBook]" />
This can be expressed with the
tmpl
namespace as follows:
<tmpl:bookTemplate book="${myBook}" />
Templates in Controllers and Tag Libraries
You can also render templates from controllers using the
render method found within controllers, which is useful for
Ajax applications:
def show = {
def b = Book.get(params.id)
render(template:"bookTemplate", model:[book:b])
}
The
render method within controllers writes directly to the response, which is the most common behaviour. If you need to instead obtain the result of template as a String you can use the
render tag:
def show = {
def b = Book.get(params.id)
String content = g.render(template:"bookTemplate", model:[book:b])
render content
}
Notice the usage of the
g.
namespace which tells Grails we want to use the
tag as method call instead of the
render method.