How to use custom tags in grails controller, services groovy file
Posted By : Ankush Kocher | 20-Nov-2014
In this blog we will use to define a custom TagLib and Tag and use in groovy files. Grails support concept of custom tag libraries and its very easy to define taglib and use tag on our gsp pages.
To create a TagLib create a Groovy class that ends with TagLib and place it within the grails-app/taglib directory. This is convention that groovy file name ends with TagLib or we can use this grails command
grails create-tag-lib [name]
e.g.
class TestTagLib { }
To define a custom tag create a Closure property that takes two arguments:
The tag attributes and the Body content:
e.g.
class TestTagLib { def myTag = { attrs, body -> } }
The attrs is a Map of the attributes of the tag and body argument is a Closure that returns the body content when invoked:
class TestTagLib { def myTag = { attrs, body -> out << body() << (attrs.happy == 'true' ? " :-)" : " :-(") } }
Now we can use this tag in our gsp page
e.g
<test:myTag happy="true">Hi John</test:myTag>
But to use our tag in groovy file,so that we pass arguments and it retrun the desire result and can be use in gsp and groovy we should not use body()<< in out
so
class TestTagLib { def myTag = { attrs, body -> out << (attrs.happy == 'true' ? " :-)" : " :-(") } }
Now we can use it in groovy file
e.g.
def var = test.myTag(['happay':'true'])
We can now also use our tag in <script></script> in gsp page
e.g
<script> var value = "${test.myTag(['happay':'true'])}" alert(value) </script>
Thanks
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Ankush Kocher
Ankush is a bright web app developer with expertise in Groovy and Grails development. Ankush is also an expert AngularJS developer.