Search code examples
grailsgsptaglib

can not get my custom taglib to work


I created my taglib using the command: "grails create-taglib TimeTag" And a skeleton tag was created called TimeTagLib.

package com.buffer

class TimeTagLib {
    static final namespace = 'myTag'
    static defaultEncodeAs = [taglib:'html']
    //static encodeAsForTags = [tagName: [taglib:'html'], otherTagName: [taglib:'none']]
    def weekNo = {attrs, body ->
        date = new Date()
        def calendar = date.toCalendar()
        def week = calendar.get(calendar.WEEK_OF_YEAR)
        out << body() << calendar.format('yy') + String.format("%02d", week+attrs.offset)
    }
}

and in the gsp-file I added this line:

<g:sortableColumn property="availW01" title="${timetaglib.weekno(offset: '0')}" />

And I get the following message: Message

Request processing failed; nested exception is org.grails.gsp.GroovyPagesException: Error evaluating expression [timetaglib.weekno(offset: '0')] on line [38]: Cannot invoke method weekno() on null object
Caused by
Cannot invoke method weekno() on null object

I just don't know what to do... I thought I followed the documentation well enough but apparently not. I have grails-3.2.4

===================THE SOLUTION ==================

TagLib:

package com.buffer

class TimeTagLib {
    static final namespace = 'myTag'
    static defaultEncodeAs = [taglib:'html']
    //static encodeAsForTags = [tagName: [taglib:'html'], otherTagName: [taglib:'none']]
    def weekNo = {attrs, body ->
        Date date = new Date()
        def calendar = date.toCalendar()
        def week = calendar.get(calendar.WEEK_OF_YEAR)
        out  << String.format("V%02d", (week+(attrs.offset as Integer)))
    }
}

The GSP:

<g:sortableColumn property="availW01" title="${myTag.weekNo(offset: "0")}" />

Solution

  • You seem to have a simple, but fundamental, misunderstanding of how to call your custom tag library. Instead of using the class name you need to use the namespace, so your tag library (in your question) would be called as such: ${myTag.weekNo(offset: 0)} or <myTag:weekNo offset="0" />.