<g:example />
3 GSP Tags
Version: 6.2.3
Table of Contents
3 GSP Tags
Now that the less attractive JSP heritage has been set aside, the following sections cover GSP’s built-in tags, which are the preferred way to define GSP pages.
The section on Tag Libraries covers how to add your own custom tag libraries. |
All built-in GSP tags start with the prefix g:
. Unlike JSP, you don’t specify any tag library imports. If a tag starts with g:
it is automatically assumed to be a GSP tag. An example GSP tag would look like:
GSP tags can also have a body such as:
<g:example>
Hello world
</g:example>
Expressions can be passed into GSP tag attributes, if an expression is not used it will be assumed to be a String value:
<g:example attr="${new Date()}">
Hello world
</g:example>
Maps can also be passed into GSP tag attributes, which are often used for a named parameter style syntax:
<g:example attr="${new Date()}" attr2="[one:1, two:2, three:3]">
Hello world
</g:example>
Note that within the values of attributes you must use single quotes for Strings:
<g:example attr="${new Date()}" attr2="[one:'one', two:'two']">
Hello world
</g:example>
With the basic syntax out the way, the next sections look at the tags that are built into Grails by default.
3.1 Variables and Scopes
Variables can be defined within a GSP using the set tag:
<g:set var="now" value="${new Date()}" />
Here we assign a variable called now
to the result of a GSP expression (which simply constructs a new java.util.Date
instance). You can also use the body of the <g:set>
tag to define a variable:
<g:set var="myHTML">
Some re-usable code on: ${new Date()}
</g:set>
The assigned value can also be a bean from the applicationContext:
<g:set var="bookService" bean="bookService" />
Variables can also be placed in one of the following scopes:
-
page
- Scoped to the current page (default) -
request
- Scoped to the current request -
flash
- Placed within flash scope and hence available for the next request -
session
- Scoped for the user session -
application
- Application-wide scope.
To specify the scope, use the scope
attribute:
<g:set var="now" value="${new Date()}" scope="request" />
3.2 Logic and Iteration
GSP also supports logical and iterative tags out of the box. For logic there are if, else and elseif tags for use with branching:
<g:if test="${session.role == 'admin'}">
<%-- show administrative functions --%>
</g:if>
<g:else>
<%-- show basic functions --%>
</g:else>
<g:each in="${[1,2,3]}" var="num">
<p>Number ${num}</p>
</g:each>
<g:set var="num" value="${1}" />
<g:while test="${num < 5 }">
<p>Number ${num++}</p>
</g:while>
3.3 Search and Filtering
If you have collections of objects you often need to sort and filter them. Use the findAll and grep tags for these tasks:
Stephen King's Books:
<g:findAll in="${books}" expr="it.author == 'Stephen King'">
<p>Title: ${it.title}</p>
</g:findAll>
The expr
attribute contains a Groovy expression that can be used as a filter. The grep tag does a similar job, for example filtering by class:
<g:grep in="${books}" filter="NonFictionBooks.class">
<p>Title: ${it.title}</p>
</g:grep>
Or using a regular expression:
<g:grep in="${books.title}" filter="~/.*?Groovy.*?/">
<p>Title: ${it}</p>
</g:grep>
The above example is also interesting due to its usage of GPath. GPath is an XPath-like language in Groovy. The books
variable is a collection of Book
instances. Since each Book
has a title
, you can obtain a list of Book titles using the expression books.title
. Groovy will auto-magically iterate the collection, obtain each title, and return a new list!
3.4 Links and Resources
GSP also features tags to help you manage linking to controllers and actions. The link tag lets you specify controller and action name pairing and it will automatically work out the link based on the URL Mappings, even if you change them! For example:
<g:link action="show" id="1">Book 1</g:link>
<g:link action="show" id="${currentBook.id}">${currentBook.name}</g:link>
<g:link controller="book">Book Home</g:link>
<g:link controller="book" action="list">Book List</g:link>
<g:link url="[action: 'list', controller: 'book']">Book List</g:link>
<g:link params="[sort: 'title', order: 'asc', author: currentBook.author]"
action="list">Book List</g:link>
3.5 Forms and Fields
Form Basics
GSP supports many different tags for working with HTML forms and fields, the most basic of which is the form tag. This is a controller/action aware version of the regular HTML form tag. The url
attribute lets you specify which controller and action to map to:
<g:form name="myForm" url="[controller:'book',action:'list']">...</g:form>
In this case we create a form called myForm
that submits to the BookController
's list
action. Beyond that, all the usual HTML attributes apply.
Form Fields
In addition to easy construction of forms, GSP supports custom tags for dealing with different types of fields, including:
-
textField - For input fields of type 'text'
-
passwordField - For input fields of type 'password'
-
checkBox - For input fields of type 'checkbox'
-
radio - For input fields of type 'radio'
-
hiddenField - For input fields of type 'hidden'
-
select - For dealing with HTML select boxes
Each of these allows GSP expressions for the value:
<g:textField name="myField" value="${myValue}" />
GSP also contains extended helper versions of the above tags such as radioGroup (for creating groups of radio tags), localeSelect, currencySelect and timeZoneSelect (for selecting locales, currencies and time zones respectively).
Multiple Submit Buttons
The age-old problem of dealing with multiple submit buttons is also handled elegantly with Grails using the actionSubmit tag. It is just like a regular submit, but lets you specify an alternative action to submit to:
<g:actionSubmit value="Some update label" action="update" />
3.6 Tags as Method Calls
Tags as method calls from GSPs
Tags return their results as a String-like object (a StreamCharBuffer
which has all of the same methods as String) instead of writing directly to the response when called as methods. For example:
Static Resource: ${createLinkTo(dir: "images", file: "logo.jpg")}
This is particularly useful for using a tag within an attribute:
<img src="${createLinkTo(dir: 'images', file: 'logo.jpg')}" />
In view technologies that don’t support this feature you have to nest tags within tags, which becomes messy quickly and often has an adverse effect of WYSIWYG tools that attempt to render the mark-up as it is not well-formed:
<img src="<g:createLinkTo dir='images' file='logo.jpg'/>" />
Tags as method calls from Controllers and Tag Libraries
You can also invoke tags from controllers and tag libraries. Tags within the default g:
namespace can be invoked without the prefix and a StreamCharBuffer
result is returned:
def imageLocation = createLinkTo(dir:"images", file:"logo.jpg").toString()
Prefix the namespace to avoid naming conflicts:
def imageLocation = g.createLinkTo(dir:"images", file:"logo.jpg").toString()
For tags that use a custom namespace, use that prefix for the method call. For example (from the CK Editor plugin):
def editor = ckeditor.editor(name: "text", width: "100%", height: "400")