无法使我的自定义taglib工作

时间:2017-02-04 19:12:27

标签: grails gsp taglib

我使用以下命令创建了我的taglib:“grails create-taglib TimeTag” 并创建了一个名为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)
    }
}

在gsp文件中我添加了这一行:

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

我收到以下消息: 消息

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

我只是不知道该怎么做......我以为我的文档很好,但显然没有。 我有grails-3.2.4

===================解决方案==================

的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)))
    }
}

GSP:

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

1 个答案:

答案 0 :(得分:2)

您似乎对如何调用自定义标记库有一个简单但基本的误解。您需要使用namespace,而不是使用类名,因此您的标记库(在您的问题中)将被调用:${myTag.weekNo(offset: 0)}<myTag:weekNo offset="0" />