SlideShare a Scribd company logo
1 of 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

More Related Content

What's hot

Functional Javascript
Functional JavascriptFunctional Javascript
Functional Javascriptguest4d57e6
 
Java script – basic auroskills (2)
Java script – basic   auroskills (2)Java script – basic   auroskills (2)
Java script – basic auroskills (2)BoneyGawande
 
GraphQL - when REST API is not enough - lessons learned
GraphQL - when REST API is not enough - lessons learnedGraphQL - when REST API is not enough - lessons learned
GraphQL - when REST API is not enough - lessons learnedMarcinStachniuk
 
GraphQL - Piękne API w Twojej Aplikacji - KrakowGraphAcademy
GraphQL - Piękne API w Twojej Aplikacji - KrakowGraphAcademyGraphQL - Piękne API w Twojej Aplikacji - KrakowGraphAcademy
GraphQL - Piękne API w Twojej Aplikacji - KrakowGraphAcademyMarcinStachniuk
 
jQuery : Talk to server with Ajax
jQuery : Talk to server with AjaxjQuery : Talk to server with Ajax
jQuery : Talk to server with AjaxWildan Maulana
 
Angular.js Primer in Aalto University
Angular.js Primer in Aalto UniversityAngular.js Primer in Aalto University
Angular.js Primer in Aalto UniversitySC5.io
 
JavaScript Functions
JavaScript FunctionsJavaScript Functions
JavaScript FunctionsColin DeCarlo
 
Wcf data services
Wcf data servicesWcf data services
Wcf data servicesEyal Vardi
 
Rochester on Rails: Introduction to Rails
Rochester on Rails: Introduction to RailsRochester on Rails: Introduction to Rails
Rochester on Rails: Introduction to RailsJason Morrison
 
PyconIE 2016 - Kajiki, the fast and validated template engine your were looki...
PyconIE 2016 - Kajiki, the fast and validated template engine your were looki...PyconIE 2016 - Kajiki, the fast and validated template engine your were looki...
PyconIE 2016 - Kajiki, the fast and validated template engine your were looki...Alessandro Molina
 
Databricks spark-knowledge-base-1
Databricks spark-knowledge-base-1Databricks spark-knowledge-base-1
Databricks spark-knowledge-base-1Rahul Kumar
 
Protocol-Oriented Networking
Protocol-Oriented NetworkingProtocol-Oriented Networking
Protocol-Oriented NetworkingMostafa Amer
 
Evolving The Java Language
Evolving The Java LanguageEvolving The Java Language
Evolving The Java LanguageQConLondon2008
 
Designing a Functional GraphQL Library
Designing a Functional GraphQL LibraryDesigning a Functional GraphQL Library
Designing a Functional GraphQL LibraryPierre Ricadat
 
The Django Book / Chapter 3: Views and URLconfs
The Django Book / Chapter 3: Views and URLconfsThe Django Book / Chapter 3: Views and URLconfs
The Django Book / Chapter 3: Views and URLconfsVincent Chien
 
JSP Standart Tag Lİbrary - JSTL
JSP Standart Tag Lİbrary - JSTLJSP Standart Tag Lİbrary - JSTL
JSP Standart Tag Lİbrary - JSTLseleciii44
 
Annotation processing and code gen
Annotation processing and code genAnnotation processing and code gen
Annotation processing and code genkoji lin
 

What's hot (20)

Functional Javascript
Functional JavascriptFunctional Javascript
Functional Javascript
 
Java script – basic auroskills (2)
Java script – basic   auroskills (2)Java script – basic   auroskills (2)
Java script – basic auroskills (2)
 
GraphQL - when REST API is not enough - lessons learned
GraphQL - when REST API is not enough - lessons learnedGraphQL - when REST API is not enough - lessons learned
GraphQL - when REST API is not enough - lessons learned
 
GraphQL - Piękne API w Twojej Aplikacji - KrakowGraphAcademy
GraphQL - Piękne API w Twojej Aplikacji - KrakowGraphAcademyGraphQL - Piękne API w Twojej Aplikacji - KrakowGraphAcademy
GraphQL - Piękne API w Twojej Aplikacji - KrakowGraphAcademy
 
jQuery : Talk to server with Ajax
jQuery : Talk to server with AjaxjQuery : Talk to server with Ajax
jQuery : Talk to server with Ajax
 
Angular.js Primer in Aalto University
Angular.js Primer in Aalto UniversityAngular.js Primer in Aalto University
Angular.js Primer in Aalto University
 
JavaScript Functions
JavaScript FunctionsJavaScript Functions
JavaScript Functions
 
Wcf data services
Wcf data servicesWcf data services
Wcf data services
 
Rochester on Rails: Introduction to Rails
Rochester on Rails: Introduction to RailsRochester on Rails: Introduction to Rails
Rochester on Rails: Introduction to Rails
 
Graphql, REST and Apollo
Graphql, REST and ApolloGraphql, REST and Apollo
Graphql, REST and Apollo
 
PyconIE 2016 - Kajiki, the fast and validated template engine your were looki...
PyconIE 2016 - Kajiki, the fast and validated template engine your were looki...PyconIE 2016 - Kajiki, the fast and validated template engine your were looki...
PyconIE 2016 - Kajiki, the fast and validated template engine your were looki...
 
Databricks spark-knowledge-base-1
Databricks spark-knowledge-base-1Databricks spark-knowledge-base-1
Databricks spark-knowledge-base-1
 
Protocol-Oriented Networking
Protocol-Oriented NetworkingProtocol-Oriented Networking
Protocol-Oriented Networking
 
Evolving The Java Language
Evolving The Java LanguageEvolving The Java Language
Evolving The Java Language
 
Nativescript angular
Nativescript angularNativescript angular
Nativescript angular
 
Designing a Functional GraphQL Library
Designing a Functional GraphQL LibraryDesigning a Functional GraphQL Library
Designing a Functional GraphQL Library
 
React и redux
React и reduxReact и redux
React и redux
 
The Django Book / Chapter 3: Views and URLconfs
The Django Book / Chapter 3: Views and URLconfsThe Django Book / Chapter 3: Views and URLconfs
The Django Book / Chapter 3: Views and URLconfs
 
JSP Standart Tag Lİbrary - JSTL
JSP Standart Tag Lİbrary - JSTLJSP Standart Tag Lİbrary - JSTL
JSP Standart Tag Lİbrary - JSTL
 
Annotation processing and code gen
Annotation processing and code genAnnotation processing and code gen
Annotation processing and code gen
 

Similar to 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 EnglishSven Haiges
 
Grails Introduction - IJTC 2007
Grails Introduction - IJTC 2007Grails Introduction - IJTC 2007
Grails Introduction - IJTC 2007Guillaume Laforge
 
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) ExtensionVMware Tanzu
 
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 ProceduresNeo4j
 
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 NetbeansCarol McDonald
 
GTLAB Installation Tutorial for SciDAC 2009
GTLAB Installation Tutorial for SciDAC 2009GTLAB Installation Tutorial for SciDAC 2009
GTLAB Installation Tutorial for SciDAC 2009marpierc
 
Dsc Charusat Learning React Part 1
Dsc Charusat Learning React Part 1 Dsc Charusat Learning React Part 1
Dsc Charusat Learning React Part 1 JainamMehta19
 
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 202Mahmoud Samir Fayed
 
Instagram filters (10-5)
Instagram filters (10-5)Instagram filters (10-5)
Instagram filters (10-5)Ivy Rueb
 
Simo's Top 30 GTM tips
Simo's Top 30 GTM tipsSimo's Top 30 GTM tips
Simo's Top 30 GTM tipsSimo Ahava
 
The Django Web Application Framework 2
The Django Web Application Framework 2The Django Web Application Framework 2
The Django Web Application Framework 2fishwarter
 
The Django Web Application Framework 2
The Django Web Application Framework 2The Django Web Application Framework 2
The Django Web Application Framework 2fishwarter
 
Introduction to Swagger
Introduction to SwaggerIntroduction to Swagger
Introduction to SwaggerKnoldus Inc.
 
The Django Web Application Framework 2
The Django Web Application Framework 2The Django Web Application Framework 2
The Django Web Application Framework 2fishwarter
 

Similar to Grails Custom Tag lib (20)

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
 
The Django Web Application Framework 2
The Django Web Application Framework 2The Django Web Application Framework 2
The Django Web Application Framework 2
 

Recently uploaded

MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontologyjohnbeverley2021
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWERMadyBayot
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
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, Adobeapidays
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
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 FresherRemote DBA Services
 
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 ...apidays
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...apidays
 
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 2024Victor Rentea
 
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 DiscoveryTrustArc
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusZilliz
 
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 SavingEdi Saputra
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 

Recently uploaded (20)

MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
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
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
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
 
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 ...
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
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
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
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
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 

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