4. INTRODUCTION
Like Java Server Pages (JSP), GSP supports the concept
of custom tag libraries. Unlike JSP, Grails' tag library
mechanism is simple, elegant and completely
reloadable at runtime.
6. DEFAULT TAGLIB
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:
<g:example />
GSP tags can also have a body such as:
<g:example>
Hello world
</g:example>
7. (Continues..)
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>
8. (Continues..)
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>
9. (Continues..)
Use the each and while tags for iteration:
<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>
10. (Continues..)
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>
11. (Continues..)
<g:textField name="myField" value="${myValue}" />
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
14. CUSTOM TAGLIB
Grails supports the concept of custom tag libraries,
where we can invoke customized action using a
custom tag in a GSP page.
TagLib is a Groovy class that ends with the convention
TagLib and placed within the grails-app/taglib
directory. Tag is a property which is assigned a block of
code that takes the tag attributes as well as the body
content.
15. (Continues..)
To create new tags use create-tag-lib command, run
"grails create-tag-lib [name]" or manually create a new
class in "grails-app/taglib/" with a name ending in
"TagLib".
grails create-tag-lib simple
Creates a tag library ‘SimpleTagLib’ for the given base
name i.e., ‘simple’ in grails-app/taglib/
class SimpleTagLib {
}
16. (Continues..)
Now to create a tag, create a Closure property that
takes two arguments: the tag attributes and the body
content:
class SimpleTagLib {
def emoticon = { attrs, body ->
out << body() << (attrs.happy == 'true' ? " :-)" : " :-(")
}
}
The attrs argument is a Map of the attributes of the
tag, whilst the body argument is a Closure that returns
the body content when invoked
18. VARIABLES AND SCOPES
● actionName - The currently executing action name
● controllerName - The currently executing controller
name
● flash - The flash object
● grailsApplication - The GrailsApplication instance
● out - The response writer for writing to the output
stream
● pageScope - A reference to the pageScope object
used for GSP rendering (i.e. the binding)
● params - The params object for retrieving request
parameters
19. (Continues..)
● pluginContextPath - The context path to the plugin
that contains the tag library
● request - The HttpServletRequest instance
● response - The HttpServletResponse instance
● servletContext - The javax.servlet.ServletContext
instance
● session - The HttpSession instance
20. SIMPLE TAGS
def dateFormat = { attrs, body ->
out << new
java.text.SimpleDateFormat(attrs.format).format(attrs.
date)
}
<g:dateFormat format="dd-MM-yyyy" date="${new
Date()}" />
21. SIMPLE TAGS - RENDERING
TEMPLATE
def formatBook = { attrs, body ->
out << "<div id="${attrs.book.id}">"
out << "Title : ${attrs.book.title}"
out << "</div>"
}
def formatBook = { attrs, body ->
out << render(template: "bookTemplate", model:
[book: attrs.book])
}
Although this approach may be tempting it is not very
clean. A better approach would be to reuse the render
tag:
22. LOGICAL TAGS
def isAdmin = { attrs, body ->
def user = attrs.user
if (user && checkUserPrivs(user)) {
out << body()
}
}
<g:isAdmin user="${myUser}">
// some restricted content
</g:isAdmin>
23. ITERATIVE TAGS
def repeat = { attrs, body ->
attrs.times?.toInteger()?.times { num ->
out << body(num)
}
}
<g:repeat times="3">
<p>Repeat this 3 times! Current repeat = ${it}</p>
</g:repeat>
24. TAG NAMESPACE
By default, tags are added to the default Grails
namespace and are used with the g: prefix in GSP pages.
However, you can specify a different namespace by
adding a static property to your TagLib class:
class SimpleTagLib {
static namespace = "my"
def example = { attrs ->
…
}
}
<my:example name="..." />
25. 4.
ACCESS TAGLIB
IN CONTROLLER
AND SERVICES
REFERENCE -
http://grails-dev.blogspot.in/2013/07/access-taglib-in-
controller-and-service.html
26. ACCESS TAGLIB IN CONTROLLER
Grails provides different tags to simplify users work like
g:createLink, g:link and so on. We can use these tags in
controllers and service too.
We can simply call the method using its namespace. For
example, lets see how to call “g:link” and
“g:formatNumber” in controller.
To get the externalized message,
g.message(code:'some.code.placed.in.messages.properties')
27. (Continues..)
To create a link,
g.link(controller:"file", action:"show",id:"${fileEntry.id}",
target:"blank"){'Go to link'}
To format a number,
g.formatNumber(number: 5000,234 , type: "number" ,
maxFractionDigits: 2)
28. ACCESS TAGLIB IN SERVICES
In some situation, we might also need to use these grails
tags in service. Like generating external links for an email,
formatting numbers or etc.
In services, grails doesn’t provide direct access to taglib in
service class, but if we want to access tags from grails tag
library or custom tag library, its not very difficult. All we
have to do is to get it from Spring context.
Note - Don’t forget to inject grailsApplication
31. BENEFITS OF TAGLIB
The advantage of taglibs is that unlike jsp tag libraries,
they require no additional configuration, no updation of
TLD descriptors, and can be reloaded at runtime without
starting the server again and again.
33. BEST PRACTICES FOR CUSTOM
TAGLIB
● Use taglib for any business logic on Views.
● Keep an individual tag light. A tag can call other tags,
and it is acceptable to break a tag into reusable sub-
tags if required.
● The TagLib is considered part of the view layer in the
MVC architecture. Avoid direct interaction with
Domain class from the taglib. For unavoidable
situation, interact with Domain class through Service
class.
● Taglib should contain more of logic than rendering,
although a little bit of rendering (a line or two) is fine.
If more rendering is required in taglib, move the HTML
code to a template gsp.