SlideShare uma empresa Scribd logo
1 de 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

Mais conteúdo relacionado

Mais procurados (20)

Java script ppt
Java script pptJava script ppt
Java script ppt
 
Oops concepts in php
Oops concepts in phpOops concepts in php
Oops concepts in php
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScript
 
jQuery
jQueryjQuery
jQuery
 
JavaScript Control Statements II
JavaScript Control Statements IIJavaScript Control Statements II
JavaScript Control Statements II
 
Scalable JavaScript Application Architecture 2012
Scalable JavaScript Application Architecture 2012Scalable JavaScript Application Architecture 2012
Scalable JavaScript Application Architecture 2012
 
Html heading
Html headingHtml heading
Html heading
 
Spring Security 3
Spring Security 3Spring Security 3
Spring Security 3
 
Html frames
Html framesHtml frames
Html frames
 
A Deeper look into Javascript Basics
A Deeper look into Javascript BasicsA Deeper look into Javascript Basics
A Deeper look into Javascript Basics
 
HTML/CSS/java Script/Jquery
HTML/CSS/java Script/JqueryHTML/CSS/java Script/Jquery
HTML/CSS/java Script/Jquery
 
jQuery
jQueryjQuery
jQuery
 
Javascript Basic
Javascript BasicJavascript Basic
Javascript Basic
 
Document Object Model
Document Object ModelDocument Object Model
Document Object Model
 
jQuery PPT
jQuery PPTjQuery PPT
jQuery PPT
 
Document Object Model (DOM)
Document Object Model (DOM)Document Object Model (DOM)
Document Object Model (DOM)
 
JavaScript - Chapter 11 - Events
 JavaScript - Chapter 11 - Events  JavaScript - Chapter 11 - Events
JavaScript - Chapter 11 - Events
 
HTML5 & Friends
HTML5 & FriendsHTML5 & Friends
HTML5 & Friends
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to Javascript
 
Angular Data Binding
Angular Data BindingAngular Data Binding
Angular Data Binding
 

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

Semelhante a Grails custom tag lib

Grails custom tag lib
Grails custom tag libGrails custom tag lib
Grails custom tag libVijay Shukla
 
Introduction to Grails Framework
Introduction to Grails FrameworkIntroduction to Grails Framework
Introduction to Grails FrameworkPT.JUG
 
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
 

Semelhante a Grails custom tag lib (20)

Grails custom tag lib
Grails custom tag libGrails custom tag lib
Grails custom tag lib
 
Introduction to Grails Framework
Introduction to Grails FrameworkIntroduction to Grails Framework
Introduction to Grails Framework
 
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
 

Mais de 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
 

Último

Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESmohitsingh558521
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 

Último (20)

Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 

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