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

About Author

Author Image
Ankush Kocher

Ankush is a bright web app developer with expertise in Groovy and Grails development. Ankush is also an expert AngularJS developer.

Request for Proposal

Name is required

Comment is required

Sending message..