SlideShare a Scribd company logo
1 of 35
GROOVY & GRAILS
CUSTOM TAGLIB
By - Vijay Shukla
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
(Continues..)
Link and Resources
1. <g:link action="show" id="1">Book 1</g:link>
2. <g:link action="show"
id="${currentBook.id}">${currentBook.name}</g:link>
3. <g:link controller="book">Book Home</g:link>
4. <g:link controller="book" action="list">Book List</g:link>
5. <g:link url="[action: 'list', controller: 'book']">Book List</g:link>
6. <g:link params="[sort: 'title', order: 'asc', author: currentBook.author]"
action="list">Book List</g:link>
3.
CUSTOM TAGLIB
ABOUT CUSTOM TAGLIB
http://docs.grails.org/2.2.1/guide/single.html#taglibs
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:
vijay@nexthoughts.com

More Related Content

What's hot

Web Integration Patterns in the Era of HTML5
Web Integration Patterns in the Era of HTML5Web Integration Patterns in the Era of HTML5
Web Integration Patterns in the Era of HTML5johnwilander
 
Introduction to couch_db
Introduction to couch_dbIntroduction to couch_db
Introduction to couch_dbRomain Testard
 
Using script db as a deaddrop to pass data between GAS, JS and Excel
Using script db as a deaddrop to pass data between GAS, JS and ExcelUsing script db as a deaddrop to pass data between GAS, JS and Excel
Using script db as a deaddrop to pass data between GAS, JS and ExcelBruce McPherson
 
MongoDB & Mongoid with Rails
MongoDB & Mongoid with RailsMongoDB & Mongoid with Rails
MongoDB & Mongoid with RailsJustin Smestad
 
Introduction to Restkit
Introduction to RestkitIntroduction to Restkit
Introduction to Restkitpetertmarks
 
Getting started with MongoDB and Scala - Open Source Bridge 2012
Getting started with MongoDB and Scala - Open Source Bridge 2012Getting started with MongoDB and Scala - Open Source Bridge 2012
Getting started with MongoDB and Scala - Open Source Bridge 2012sullis
 
VBA API for scriptDB primer
VBA API for scriptDB primerVBA API for scriptDB primer
VBA API for scriptDB primerBruce McPherson
 
Mongoid in the real world
Mongoid in the real worldMongoid in the real world
Mongoid in the real worldKevin Faustino
 
Web II - 02 - How ASP.NET Works
Web II - 02 - How ASP.NET WorksWeb II - 02 - How ASP.NET Works
Web II - 02 - How ASP.NET WorksRandy Connolly
 
JSP Standart Tag Lİbrary - JSTL
JSP Standart Tag Lİbrary - JSTLJSP Standart Tag Lİbrary - JSTL
JSP Standart Tag Lİbrary - JSTLseleciii44
 
Java Persistence Frameworks for MongoDB
Java Persistence Frameworks for MongoDBJava Persistence Frameworks for MongoDB
Java Persistence Frameworks for MongoDBTobias Trelle
 
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />tutorialsruby
 

What's hot (20)

Web Integration Patterns in the Era of HTML5
Web Integration Patterns in the Era of HTML5Web Integration Patterns in the Era of HTML5
Web Integration Patterns in the Era of HTML5
 
Ridingapachecamel
RidingapachecamelRidingapachecamel
Ridingapachecamel
 
Introduction to couch_db
Introduction to couch_dbIntroduction to couch_db
Introduction to couch_db
 
Using script db as a deaddrop to pass data between GAS, JS and Excel
Using script db as a deaddrop to pass data between GAS, JS and ExcelUsing script db as a deaddrop to pass data between GAS, JS and Excel
Using script db as a deaddrop to pass data between GAS, JS and Excel
 
MongoDB & Mongoid with Rails
MongoDB & Mongoid with RailsMongoDB & Mongoid with Rails
MongoDB & Mongoid with Rails
 
Why Django for Web Development
Why Django for Web DevelopmentWhy Django for Web Development
Why Django for Web Development
 
Introduction to Restkit
Introduction to RestkitIntroduction to Restkit
Introduction to Restkit
 
Getting started with MongoDB and Scala - Open Source Bridge 2012
Getting started with MongoDB and Scala - Open Source Bridge 2012Getting started with MongoDB and Scala - Open Source Bridge 2012
Getting started with MongoDB and Scala - Open Source Bridge 2012
 
VBA API for scriptDB primer
VBA API for scriptDB primerVBA API for scriptDB primer
VBA API for scriptDB primer
 
Mongoid in the real world
Mongoid in the real worldMongoid in the real world
Mongoid in the real world
 
Web II - 02 - How ASP.NET Works
Web II - 02 - How ASP.NET WorksWeb II - 02 - How ASP.NET Works
Web II - 02 - How ASP.NET Works
 
JSON
JSONJSON
JSON
 
Java script
Java scriptJava script
Java script
 
JSP Standart Tag Lİbrary - JSTL
JSP Standart Tag Lİbrary - JSTLJSP Standart Tag Lİbrary - JSTL
JSP Standart Tag Lİbrary - JSTL
 
Java Persistence Frameworks for MongoDB
Java Persistence Frameworks for MongoDBJava Persistence Frameworks for MongoDB
Java Persistence Frameworks for MongoDB
 
Java script
Java scriptJava script
Java script
 
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />
 
Twentyten
TwentytenTwentyten
Twentyten
 
MongoDB Webtech conference 2010
MongoDB Webtech conference 2010MongoDB Webtech conference 2010
MongoDB Webtech conference 2010
 
RicoAjaxEngine
RicoAjaxEngineRicoAjaxEngine
RicoAjaxEngine
 

Similar to Grails custom tag lib

Grails Introduction - IJTC 2007
Grails Introduction - IJTC 2007Grails Introduction - IJTC 2007
Grails Introduction - IJTC 2007Guillaume Laforge
 
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
 
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
 
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
 
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
 
GTLAB Installation Tutorial for SciDAC 2009
GTLAB Installation Tutorial for SciDAC 2009GTLAB Installation Tutorial for SciDAC 2009
GTLAB Installation Tutorial for SciDAC 2009marpierc
 
Scala Frameworks for Web Application 2016
Scala Frameworks for Web Application 2016Scala Frameworks for Web Application 2016
Scala Frameworks for Web Application 2016takezoe
 
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
 
Django - Framework web para perfeccionistas com prazos
Django - Framework web para perfeccionistas com prazosDjango - Framework web para perfeccionistas com prazos
Django - Framework web para perfeccionistas com prazosIgor Sobreira
 
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
 
Apache Calcite (a tutorial given at BOSS '21)
Apache Calcite (a tutorial given at BOSS '21)Apache Calcite (a tutorial given at BOSS '21)
Apache Calcite (a tutorial given at BOSS '21)Julian Hyde
 
Java script tutorial
Java script tutorialJava script tutorial
Java script tutorialDoeun KOCH
 

Similar to Grails custom tag lib (20)

Grails Introduction - IJTC 2007
Grails Introduction - IJTC 2007Grails Introduction - IJTC 2007
Grails Introduction - IJTC 2007
 
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
 
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
 
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
 
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
 
GTLAB Installation Tutorial for SciDAC 2009
GTLAB Installation Tutorial for SciDAC 2009GTLAB Installation Tutorial for SciDAC 2009
GTLAB Installation Tutorial for SciDAC 2009
 
Jstl 8
Jstl 8Jstl 8
Jstl 8
 
Scala Frameworks for Web Application 2016
Scala Frameworks for Web Application 2016Scala Frameworks for Web Application 2016
Scala Frameworks for Web Application 2016
 
SVCC Intro to Grails
SVCC Intro to GrailsSVCC Intro to Grails
SVCC Intro to Grails
 
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
 
Discovering Django - zekeLabs
Discovering Django - zekeLabsDiscovering Django - zekeLabs
Discovering Django - zekeLabs
 
Django - Framework web para perfeccionistas com prazos
Django - Framework web para perfeccionistas com prazosDjango - Framework web para perfeccionistas com prazos
Django - Framework web para perfeccionistas com prazos
 
Dsc Charusat Learning React Part 1
Dsc Charusat Learning React Part 1 Dsc Charusat Learning React Part 1
Dsc Charusat Learning React Part 1
 
Unit 4(it workshop)
Unit 4(it workshop)Unit 4(it workshop)
Unit 4(it workshop)
 
Apache Calcite (a tutorial given at BOSS '21)
Apache Calcite (a tutorial given at BOSS '21)Apache Calcite (a tutorial given at BOSS '21)
Apache Calcite (a tutorial given at BOSS '21)
 
Java script tutorial
Java script tutorialJava script tutorial
Java script tutorial
 
Grails 101
Grails 101Grails 101
Grails 101
 

More from Vijay Shukla (20)

Introduction of webpack 4
Introduction of webpack 4Introduction of webpack 4
Introduction of webpack 4
 
Preview of Groovy 3
Preview of Groovy 3Preview of Groovy 3
Preview of Groovy 3
 
Jython
JythonJython
Jython
 
Groovy closures
Groovy closuresGroovy closures
Groovy closures
 
Groovy
GroovyGroovy
Groovy
 
Grails services
Grails servicesGrails services
Grails services
 
Grails plugin
Grails pluginGrails plugin
Grails plugin
 
Grails domain
Grails domainGrails domain
Grails domain
 
Grails
GrailsGrails
Grails
 
Gorm
GormGorm
Gorm
 
Controller
ControllerController
Controller
 
Config BuildConfig
Config BuildConfigConfig BuildConfig
Config BuildConfig
 
Command object
Command objectCommand object
Command object
 
Boot strap.groovy
Boot strap.groovyBoot strap.groovy
Boot strap.groovy
 
Vertx
VertxVertx
Vertx
 
Custom plugin
Custom pluginCustom plugin
Custom plugin
 
Spring security
Spring securitySpring security
Spring security
 
REST
RESTREST
REST
 
Config/BuildConfig
Config/BuildConfigConfig/BuildConfig
Config/BuildConfig
 
GORM
GORMGORM
GORM
 

Recently uploaded

Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...aditisharan08
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfPower Karaoke
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 

Recently uploaded (20)

Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdf
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 

Grails custom tag lib

  • 1. GROOVY & GRAILS CUSTOM TAGLIB By - Vijay Shukla
  • 2. 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
  • 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.
  • 5. 2. DEFAULT TAGLIB BRIEF ABOUT DEFAULT TAGLIB http://docs.grails.org/2.2.1/guide/single.html#tags
  • 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
  • 12. (Continues..) Link and Resources 1. <g:link action="show" id="1">Book 1</g:link> 2. <g:link action="show" id="${currentBook.id}">${currentBook.name}</g:link> 3. <g:link controller="book">Book Home</g:link> 4. <g:link controller="book" action="list">Book List</g:link> 5. <g:link url="[action: 'list', controller: 'book']">Book List</g:link> 6. <g:link params="[sort: 'title', order: 'asc', author: currentBook.author]" action="list">Book List</g:link>
  • 13. 3. CUSTOM TAGLIB ABOUT CUSTOM TAGLIB http://docs.grails.org/2.2.1/guide/single.html#taglibs
  • 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.
  • 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: vijay@nexthoughts.com