Grails 3 call taglib from a service

徘徊边缘 提交于 2021-02-08 10:08:00

问题


I'm trying to use grails internal taglib from a service but I receive this error:

No signature of method: MyService.message() is applicable for argument types: (java.util.LinkedHashMap) values: [[code:default.app.name]]

This is the code I'm using:

class MyService {

    def myMethod() {
        def appName = message(code: 'default.app.name')
    }

}

回答1:


Grails 3

The solution is to inject the grailsApplication object and use its context to get the taglib bean:

class MyService {

    def grailsApplication

    def myMethod() {
        def g = grailsApplication.mainContext.getBean('org.grails.plugins.web.taglib.ApplicationTagLib')
        def appName = g.message(code: 'default.app.name')
    }

}

Grails 2

With older grails version the class package is slightly different:

def g = grailsApplication.mainContext.getBean('org.codehaus.groovy.grails.plugins.web.taglib.ApplicationTagLib')

If you try to use this package with newer grails version (3+), you'll receive an error:

No bean named 'org.codehaus.groovy.grails.plugins.web.taglib.ApplicationTagLib' is defined.    

Custom taglib

With any version, if you need to use your custom taglib from a service just use a code like this:

def c = grailsApplication.mainContext.getBean('my.pkg.HelpfulTagLib')


来源:https://stackoverflow.com/questions/36926186/grails-3-call-taglib-from-a-service

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!