Like
Java Server Pages (JSP), GSP supports the concept of custom tag libraries. Unlike JSP, Grails tag library mechanism is simply, elegant and completely reload-able at runtime.
Quite simply, to create a tag library create a Groovy class that ends with the convention
TagLib
and place it within the
grails-app/taglib
directory:
Now to create a tag simply create property that is assigned a block of code that takes two arguments: The tag attributes and the body content:
class SimpleTagLib {
def simple = { attrs, body -> }
}
The
attrs
argument is a simple map of the attributes of the tag, whilst the
body
argument is another invokable block of code that returns the body content:
class SimpleTagLib {
def emoticon = { attrs, body ->
out << body() << (attrs.happy == 'true' ? " :-)" : " :-(")
}
}
As demonstrated above there is an implicit
out
variable that refers to the output
Writer
which you can use to append content to the response. Then you can simply reference the tag inside your GSP, no imports necessary:
<g:emoticon happy="true">Hi John</g:emoticon>