Grails custom tag lib

35
GROOVY & GRAILS CUSTOM TAGLIB By - Ali Tanwir

Transcript of Grails custom tag lib

Page 1: Grails custom tag lib

GROOVY & GRAILS

CUSTOM TAGLIB

By - Ali Tanwir

Page 2: Grails custom tag lib

Hello!I AM ALI TANWIR

You can email me at:[email protected]

Page 3: Grails custom tag lib

AGENDA● INTRODUCTION● DEFAULT TAGLIB● CUSTOM TAGLIB

○ VARIABLES AND SCOPE○ SIMPLE TAGS○ LOGICAL TAGS○ ITERATIVE TAGS○ TAG NAMESPACE

● ACCESS TAGLIB IN CONTROLLER AND SERVICES● BENEFITS● BEST PRACTICES FOR CUSTOM TAGLIB● REFERENCES

Page 4: Grails custom tag lib

1.INTRODUCTION

Page 5: Grails custom tag lib

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.

Page 6: Grails custom tag lib

2.DEFAULT TAGLIB

BRIEF ABOUT DEFAULT TAGLIBhttp://docs.grails.org/2.2.1/guide/single.html#tags

Page 7: Grails custom tag lib

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>

Page 8: Grails custom tag lib

(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>

Page 9: Grails custom tag lib

(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>

Page 10: Grails custom tag lib

(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>

Page 11: Grails custom tag lib

(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>

Page 12: Grails custom tag lib

(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

Page 13: Grails custom tag lib

3.CUSTOM TAGLIB

ABOUT CUSTOM TAGLIBhttp://docs.grails.org/2.2.1/guide/single.html#taglibs

Page 14: Grails custom tag lib

CUSTOM TAGLIBGrails 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.

Page 15: Grails custom tag lib

(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 {

}

Page 16: Grails custom tag lib

(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

Page 17: Grails custom tag lib

(Continues..)Referencing the tag inside GSP; no imports are necessary:

<g:emoticon happy="true">Hi John</g:emoticon>

Page 18: Grails custom tag lib

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

Page 19: Grails custom tag lib

(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

Page 20: Grails custom tag lib

SIMPLE TAGSdef dateFormat = { attrs, body -> out << new java.text.SimpleDateFormat(attrs.format).format(attrs.date)}

<g:dateFormat format="dd-MM-yyyy" date="${new Date()}" />

Page 21: Grails custom tag lib

SIMPLE TAGS - RENDERING TEMPLATEdef 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:

Page 22: Grails custom tag lib

LOGICAL TAGSdef isAdmin = { attrs, body -> def user = attrs.user if (user && checkUserPrivs(user)) { out << body() }}

<g:isAdmin user="${myUser}"> // some restricted content</g:isAdmin>

Page 23: Grails custom tag lib

ITERATIVE TAGSdef 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>

Page 24: Grails custom tag lib

TAG NAMESPACEBy 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="..." />

Page 25: Grails custom tag lib

4.ACCESS TAGLIB IN CONTROLLER AND SERVICES

REFERENCE - http://grails-dev.blogspot.in/2013/07/access-taglib-in-controller-and-service.html

Page 26: Grails custom tag lib

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')

Page 27: Grails custom tag lib

(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)

Page 28: Grails custom tag lib

ACCESS TAGLIB IN SERVICESIn 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

Page 29: Grails custom tag lib

(Continues..)def g = grailsApplication.mainContext.getBean('org.codehaus.groovy.grails.plugins.web.taglib.ApplicationTagLib')

To access custom tags which were written and placed in tagLib directory,

def c = grailsApplication.mainContext.getBean('com.custom.MyCustomTagLib')

Page 30: Grails custom tag lib

5.BENEFITS

Page 31: Grails custom tag lib

BENEFITS OF TAGLIBThe 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.

Page 32: Grails custom tag lib

5.CUSTOM TAGLIB - BEST PRACTICES

Page 33: Grails custom tag lib

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.

Page 34: Grails custom tag lib

REFERENCES● http://docs.grails.org/2.2.1/guide/single.html#tags● http://docs.grails.org/2.2.1/guide/single.html#taglibs● http://docs.grails.org/2.2.1/ref/Command%20Line/create-tag-lib.

html● http://docs.grails.org/2.2.1/ref/Tags/render.html● http://grails-dev.blogspot.in/2013/07/access-taglib-in-controller-

and-service.html

Page 35: Grails custom tag lib

THANKS!Any questions?

You can email me at:[email protected]