Creating custom taglib In Grails

Posted By : Nishtha Singh | 30-Jul-2013

Custom TagLib in Grails

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.

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 n again.

 

Here is an example below which shows how to create custom taglib

 

To create new tags, run "grails create-tag-lib" or manually create a new class in "grails-app/taglib/" with a name ending in "TagLib". (If we use "ApplicationTabLib.groovy", we will no longer be able to use the standard grails tags.)

  • Simple Taglib:

    To create a simple tag we add a new closure property that takes first argument as the attributes of the tag and the second which is the body content....The attrs argument is a Map of the attributes of the tag, while the body argument is a Closure that returns the body content when invoked. The syntax is shown below:

    
    class SimpleTagLib {
        def simple = { attrs, body -> }
    }
    

    attrs and body are dynamic variables hence they may or may not be included in the custom taglib.

    
    class CategoryTaglib {
    		def showResult = {
    				def results=StudentDB.findAll()
    				results.sort{
    		stu1,stu2->stu1.name.compareToIgnoreCase(stu2.name)
    				}
    		
    out<< render(view:"showResult",model:[results:results])
    }
    	}
    

    And in the gsp we can access the taglib as shown below:

    
    
    
    

    So the output would be the response of the rendered template.

    Name: nishtha
    RollNo: 101
    Age: 21
    Marks: 98
    Stream: sci
    Contact: 778890098
    Name: richa
    RollNo: 103 Age: 22 Marks: 83 Stream: sci Contact: 76876989080

    Name: suraj RollNo: 102 Age: 22 Marks: 38 Stream: sci Contact: 7788998098

    Hence, custom taglib helps us reuse the code elsewhere throughout the application just like the grails predefined tags are used in the gsps.

  • Taglibs with conditional loops

    We can also create logical tags where the body of the tag is only output once a set of conditions have been met. An example of this may be a set of security tags:

    In the controller’s action we can specify a condition for checking whether the marks of a student is between 40-100 or not.

    
    class CategoryTaglib {
    def getScore = { attrs, body ->
        def marks = attrs.marks
        def studentPassList =StudentDB.findAllByMarks(marks)
    if(studentPassList?.marks>= "40" && studentPassList?.marks <= "100")
    out<< render(view:"result",model:[studentPassList:studentPassList] )
    
        }
    }
    }
    

    Inside the view I have just iterated the list of pass students and shown them as response.

    
    
    
    
    
    
      Name: ${it.name}
      
      RollNo: ${it.rollNo}
      
     Age: ${it.age}
      
     Marks: ${it.marks}
      
    Stream: ${it.stream}
      
      Contact: ${it.contact}
    
       
    

    So, logical tags are those where prechecking of checking conditions is done while implementation of body. As a result, the output is as under:


    Name: nishtha RollNo: 101 Age: 21 Marks: 98 Stream: sci Contact: 778890098

    Name: richa RollNo: 103 Age: 22 Marks: 83 Stream: sci Contact: 76876989080
  • Taglib for repetitive output

    We can also create a taglib where we want the action to be repeated a specific number of times. Iterative tags are those in which the body of the tag can be invoked multiple times.

    In this example we check for a check attribute and if it exists convert it to a number, then use Groovy's times method to iterate the specified number of times: In the controller I have this action named repeat which accepts the marks value in params from a gsp and implements the iterative tag in the following manner

    
    class CategoryTaglib {
    def displayMarks()={		
    def highestMarksList=StudentDB.findAllByMarks(marks)
    if(highestMarksList >= 95)
    {
       def repeat = { attrs, body ->
        attrs.check?.toInteger()?.times { num ->
             out << body(num)
        }
    out << render(view:"result",model:[highestMarksList:highestMarksList]) 
    				
    }
    }
    

    And in the gsp, we can pass the value of the times variable as shown below:

    
    
    
    
    
      Name: ${it.name}
      
      RollNo: ${it.rollNo}
      
     Age: ${it.age}
      
     Marks: ${it.marks}
      
    Stream: ${it.stream}
      
      Contact: ${it.contact}
    
    
    

    congratulations!!!

    In the above example, for improving readability, we can also assign variable name to the num attribute.... For instance I have used var as the name of the variable here and hence I have also used parenthesis around the variable name in the line out << body((var):num) so that Groovy doesn’t misinterpret it as String key value.

    
    def displayMarks()={		
    def highestMarksList=StudentDB.findAllByMarks(marks)
    if(highestMarksList >= 95)
    {
        def var = attrs.var ?: "num"
    
        def repeat = { attrs, body ->
        attrs.times?.toInteger()?.times { num ->
           out << body((var):num)
     }
    }
    out << render(view:"result",model:[highestMarksList:highestMarksList])
    }
    
  • Taglib Namespaces

    By default, tags are added to the default Grails namespace and are used with the g: prefix in GSP pages. .We can create our own namespace by specifying a static property in the Taglib class.

    Im using the same example as for the simple tag and with the namespace property:

    
    class CategoryTaglib {
            static namespace = “category”
    		def showResult = {
    				def results=StudentDB.findAll()
    				results.sort{
    		stu1,stu2->stu1.name.compareToIgnoreCase(stu2.name)
    				}
    		
    out<< render(view:"showResult",model:[results:results])
    }
    	}
    

    And in the gsp also the tag woud be accessed in a different manner as shown below. Taglibs are particularly useful for plugins.

    
    
    
    
  • Taglib return values

    Custom Taglibs can return direct object values as well.. As we know, Taglib class returns the object of org.codehaus.groovy.grails.web.util.StreamCharBuffer class by default thereby improving performance.

    Tag libraries can also return direct object values.Object returning tag names are stored in a static returnObjectForTags property in the tag library class. For instance implementing this in the same example. Inside the controller:

    class CategoryTaglib {
        static namespace = "category"
        static returnObjectForTags = ['showResult']
      def showResult = {
    				def results=StudentDB.findAll()
    				results.sort{
    		stu1,stu2->stu1.name.compareToIgnoreCase(stu2.name)
    				}
    		
    out<< render(view:"showResult",model:[results:results])
        }
    }
    

    The code for gsp would remains the same as there is no change in the method of accessing the tag

About Author

Author Image
Nishtha Singh

Nistha is a bright Groovy and Grails developer and have worked on development of various SaaS applications using Grails technologies. Nistha's hobbies are poetry and glass painting.

Request for Proposal

Name is required

Comment is required

Sending message..