SlideShare ist ein Scribd-Unternehmen logo
1 von 35
GROOVY & GRAILS
CUSTOM TAGLIB
By - Ali Tanwir
Hello!
I AM ALI TANWIR
You can email me at:
ali.tanwir@nexthoughts.com
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
1.
INTRODUCTION
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.
2.
DEFAULT TAGLIB
BRIEF ABOUT DEFAULT TAGLIB
http://docs.grails.org/2.2.1/guide/single.html#tags
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>
(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>
(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>
(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>
(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>
(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
3.
CUSTOM TAGLIB
ABOUT CUSTOM TAGLIB
http://docs.grails.org/2.2.1/guide/single.html#taglib
s
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.
(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 {
}
(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
(Continues..)
Referencing the tag inside GSP; no imports are
necessary:
<g:emoticon happy="true">Hi John</g:emoticon>
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
(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
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()}" />
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:
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>
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>
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="..." />
4.
ACCESS TAGLIB IN
CONTROLLER
AND SERVICES
REFERENCE -
http://grails-dev.blogspot.in/2013/07/access-
taglib-in-controller-and-service.html
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')
(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)
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
(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')
5.
BENEFITS
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.
5.
CUSTOM TAGLIB - BEST
PRACTICES
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.
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
THANKS!
Any questions?
You can email me at:
ali.tanwir@nexthoughts.com

Weitere ähnliche Inhalte

Was ist angesagt?

Was ist angesagt? (20)

Arrays in php
Arrays in phpArrays in php
Arrays in php
 
Java collection
Java collectionJava collection
Java collection
 
04 curso poo Herencia
04 curso poo Herencia04 curso poo Herencia
04 curso poo Herencia
 
Generics in java
Generics in javaGenerics in java
Generics in java
 
L11 array list
L11 array listL11 array list
L11 array list
 
Introduction to Grails Framework
Introduction to Grails FrameworkIntroduction to Grails Framework
Introduction to Grails Framework
 
Java 9 New Features
Java 9 New FeaturesJava 9 New Features
Java 9 New Features
 
Corso pratico di C# - 2013
Corso pratico di C# - 2013Corso pratico di C# - 2013
Corso pratico di C# - 2013
 
Object oriented programming in python
Object oriented programming in pythonObject oriented programming in python
Object oriented programming in python
 
Trigger in mysql
Trigger in mysqlTrigger in mysql
Trigger in mysql
 
Celery의 빛과 그림자
Celery의 빛과 그림자Celery의 빛과 그림자
Celery의 빛과 그림자
 
Presentación funciones
Presentación funcionesPresentación funciones
Presentación funciones
 
Java Collections Tutorials
Java Collections TutorialsJava Collections Tutorials
Java Collections Tutorials
 
Malli: inside data-driven schemas
Malli: inside data-driven schemasMalli: inside data-driven schemas
Malli: inside data-driven schemas
 
9. Input Output in java
9. Input Output in java9. Input Output in java
9. Input Output in java
 
clean code book summary - uncle bob - English version
clean code book summary - uncle bob - English versionclean code book summary - uncle bob - English version
clean code book summary - uncle bob - English version
 
DBIx::Class beginners
DBIx::Class beginnersDBIx::Class beginners
DBIx::Class beginners
 
Java Generics Introduction - Syntax Advantages and Pitfalls
Java Generics Introduction - Syntax Advantages and PitfallsJava Generics Introduction - Syntax Advantages and Pitfalls
Java Generics Introduction - Syntax Advantages and Pitfalls
 
XML
XMLXML
XML
 
C# Inheritance
C# InheritanceC# Inheritance
C# Inheritance
 

Andere mochten auch

Andere mochten auch (20)

Grails internationalization-160524154831
Grails internationalization-160524154831Grails internationalization-160524154831
Grails internationalization-160524154831
 
Bootcamp linux commands
Bootcamp linux commandsBootcamp linux commands
Bootcamp linux commands
 
G pars
G parsG pars
G pars
 
Spring boot
Spring bootSpring boot
Spring boot
 
Twilio
TwilioTwilio
Twilio
 
Gorm
GormGorm
Gorm
 
MetaProgramming with Groovy
MetaProgramming with GroovyMetaProgramming with Groovy
MetaProgramming with Groovy
 
Actors model in gpars
Actors model in gparsActors model in gpars
Actors model in gpars
 
Java reflection
Java reflectionJava reflection
Java reflection
 
Grails services
Grails servicesGrails services
Grails services
 
Grails Controllers
Grails ControllersGrails Controllers
Grails Controllers
 
Grails with swagger
Grails with swaggerGrails with swagger
Grails with swagger
 
Groovy DSL
Groovy DSLGroovy DSL
Groovy DSL
 
Grails domain classes
Grails domain classesGrails domain classes
Grails domain classes
 
Command objects
Command objectsCommand objects
Command objects
 
RESTEasy
RESTEasyRESTEasy
RESTEasy
 
Reactive java - Reactive Programming + RxJava
Reactive java - Reactive Programming + RxJavaReactive java - Reactive Programming + RxJava
Reactive java - Reactive Programming + RxJava
 
Introduction to thymeleaf
Introduction to thymeleafIntroduction to thymeleaf
Introduction to thymeleaf
 
Spring Framework
Spring FrameworkSpring Framework
Spring Framework
 
Apache tika
Apache tikaApache tika
Apache tika
 

Ähnlich wie Grails custom tag lib

Agile web development Groovy Grails with Netbeans
Agile web development Groovy Grails with NetbeansAgile web development Groovy Grails with Netbeans
Agile web development Groovy Grails with Netbeans
Carol McDonald
 
GTLAB Installation Tutorial for SciDAC 2009
GTLAB Installation Tutorial for SciDAC 2009GTLAB Installation Tutorial for SciDAC 2009
GTLAB Installation Tutorial for SciDAC 2009
marpierc
 

Ähnlich wie Grails custom tag lib (20)

Grails custom tag lib
Grails custom tag libGrails custom tag lib
Grails custom tag lib
 
Grails 0.3-SNAPSHOT Presentation WJAX 2006 English
Grails 0.3-SNAPSHOT Presentation WJAX 2006 EnglishGrails 0.3-SNAPSHOT Presentation WJAX 2006 English
Grails 0.3-SNAPSHOT Presentation WJAX 2006 English
 
Jstl 8
Jstl 8Jstl 8
Jstl 8
 
SVCC Intro to Grails
SVCC Intro to GrailsSVCC Intro to Grails
SVCC Intro to Grails
 
Grails Introduction - IJTC 2007
Grails Introduction - IJTC 2007Grails Introduction - IJTC 2007
Grails Introduction - IJTC 2007
 
Simplify Access to Data from Pivotal GemFire Using the GraphQL (G2QL) Extension
Simplify Access to Data from Pivotal GemFire Using the GraphQL (G2QL) ExtensionSimplify Access to Data from Pivotal GemFire Using the GraphQL (G2QL) Extension
Simplify Access to Data from Pivotal GemFire Using the GraphQL (G2QL) Extension
 
Discovering Django - zekeLabs
Discovering Django - zekeLabsDiscovering Django - zekeLabs
Discovering Django - zekeLabs
 
Boost Your Neo4j with User-Defined Procedures
Boost Your Neo4j with User-Defined ProceduresBoost Your Neo4j with User-Defined Procedures
Boost Your Neo4j with User-Defined Procedures
 
Agile web development Groovy Grails with Netbeans
Agile web development Groovy Grails with NetbeansAgile web development Groovy Grails with Netbeans
Agile web development Groovy Grails with Netbeans
 
AngularJS Workshop
AngularJS WorkshopAngularJS Workshop
AngularJS Workshop
 
GTLAB Installation Tutorial for SciDAC 2009
GTLAB Installation Tutorial for SciDAC 2009GTLAB Installation Tutorial for SciDAC 2009
GTLAB Installation Tutorial for SciDAC 2009
 
Dsc Charusat Learning React Part 1
Dsc Charusat Learning React Part 1 Dsc Charusat Learning React Part 1
Dsc Charusat Learning React Part 1
 
The Ring programming language version 1.8 book - Part 91 of 202
The Ring programming language version 1.8 book - Part 91 of 202The Ring programming language version 1.8 book - Part 91 of 202
The Ring programming language version 1.8 book - Part 91 of 202
 
Instagram filters (10-5)
Instagram filters (10-5)Instagram filters (10-5)
Instagram filters (10-5)
 
Grails 101
Grails 101Grails 101
Grails 101
 
Simo's Top 30 GTM tips
Simo's Top 30 GTM tipsSimo's Top 30 GTM tips
Simo's Top 30 GTM tips
 
Unit 4(it workshop)
Unit 4(it workshop)Unit 4(it workshop)
Unit 4(it workshop)
 
The Django Web Application Framework 2
The Django Web Application Framework 2The Django Web Application Framework 2
The Django Web Application Framework 2
 
The Django Web Application Framework 2
The Django Web Application Framework 2The Django Web Application Framework 2
The Django Web Application Framework 2
 
Introduction to Swagger
Introduction to SwaggerIntroduction to Swagger
Introduction to Swagger
 

Mehr von NexThoughts Technologies

Mehr von NexThoughts Technologies (20)

Alexa skill
Alexa skillAlexa skill
Alexa skill
 
GraalVM
GraalVMGraalVM
GraalVM
 
Docker & kubernetes
Docker & kubernetesDocker & kubernetes
Docker & kubernetes
 
Apache commons
Apache commonsApache commons
Apache commons
 
HazelCast
HazelCastHazelCast
HazelCast
 
MySQL Pro
MySQL ProMySQL Pro
MySQL Pro
 
Microservice Architecture using Spring Boot with React & Redux
Microservice Architecture using Spring Boot with React & ReduxMicroservice Architecture using Spring Boot with React & Redux
Microservice Architecture using Spring Boot with React & Redux
 
Swagger
SwaggerSwagger
Swagger
 
Solid Principles
Solid PrinciplesSolid Principles
Solid Principles
 
Arango DB
Arango DBArango DB
Arango DB
 
Jython
JythonJython
Jython
 
Introduction to TypeScript
Introduction to TypeScriptIntroduction to TypeScript
Introduction to TypeScript
 
Smart Contract samples
Smart Contract samplesSmart Contract samples
Smart Contract samples
 
My Doc of geth
My Doc of gethMy Doc of geth
My Doc of geth
 
Geth important commands
Geth important commandsGeth important commands
Geth important commands
 
Ethereum genesis
Ethereum genesisEthereum genesis
Ethereum genesis
 
Ethereum
EthereumEthereum
Ethereum
 
Springboot Microservices
Springboot MicroservicesSpringboot Microservices
Springboot Microservices
 
An Introduction to Redux
An Introduction to ReduxAn Introduction to Redux
An Introduction to Redux
 
Google authentication
Google authenticationGoogle authentication
Google authentication
 

Kürzlich hochgeladen

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 

Kürzlich hochgeladen (20)

Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 

Grails custom tag lib

  • 1. GROOVY & GRAILS CUSTOM TAGLIB By - Ali Tanwir
  • 2. Hello! I AM ALI TANWIR You can email me at: ali.tanwir@nexthoughts.com
  • 3. 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
  • 5. 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. 2. DEFAULT TAGLIB BRIEF ABOUT DEFAULT TAGLIB http://docs.grails.org/2.2.1/guide/single.html#tags
  • 7. 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>
  • 8. (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>
  • 9. (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>
  • 10. (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>
  • 11. (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>
  • 12. (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
  • 13. 3. CUSTOM TAGLIB ABOUT CUSTOM TAGLIB http://docs.grails.org/2.2.1/guide/single.html#taglib s
  • 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
  • 17. (Continues..) Referencing the tag inside GSP; no imports are necessary: <g:emoticon happy="true">Hi John</g:emoticon>
  • 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
  • 29. (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')
  • 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.
  • 32. 5. CUSTOM TAGLIB - BEST PRACTICES
  • 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.
  • 34. 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
  • 35. THANKS! Any questions? You can email me at: ali.tanwir@nexthoughts.com