Grails tag libraries are designed to provide content formatting capabilities right on a GSP page. The 'tag' is an action that can be declared in a form of an HTML element. This action can accept an enclosed content and parameters defined as the element attributes to render a modified HTML. For instance, the following built-in tag iterates and renders each element of the list object using the template specified in the content:
1 2 3 4 5 |
|
The output:
1 2 3 |
|
This post is intended for those who do not have aby knowledge of Grails tag libraries, and looking for a way to quickly grasp the general concepts without diving into the documentation.
Creating a custom tag
Custom tag libraries are represented by classes located in the 'grails-app/taglib' project directory. Any property of a tag library class, assigned to a closure which takes two arguments, is a recognized as a tag action:
1 2 3 4 5 6 7 8 |
|
Let's create the 'renderList' action which takes a list of objects and renders its values using styled 'span' elements:
1 2 3 4 5 6 7 8 9 10 11 12 |
|
Now, define the renderList
tag on a GSP page using the closure name:
1
|
|
This results in the following output:
1 2 3 |
|
Referencing a tag variable
You can pass variables to a content enclosed by a tag and use the enclosed content as a template:
1 2 |
|
1 2 3 4 |
|
For example, here is the 'iterator' action which repeats its enclosed content, this action defines the 'i' variable that keeps the iteration number:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
|
The GSP page code:
1
|
|
or the same code without predefined iterator, when the variable i
is used by default:
1
|
|
Defining a tag library namespace
Namespaces help to group tag actions and isolate tag libraries in order to avoid naming conflicts. You can define
a custom namespace with the static namespace
property:
1 2 3 4 |
|
For instance:
1 2 3 4 5 6 7 |
|
Now, to use the iterate
tag action, you should specify the admin
namespace as the tag prefix:
1
|
|
Conclusion
Grails tag libraries are very flexible, and allow to access most of the application scopes or even load data from a database. The only thing to remember here is that they are invoked on a GSP page, and GSP pages are not intended for data loading and processing. Such a heavy lifting should be done by services and controllers, while content formatting must be left to tag libraries which are way more readable than the embedded code blocks.
The post is written for the Grails version 1.3.7