Can I use grails tag outside of GSP?

2019-01-17 22:07发布

For example, i can put

 <g:createLink controller="user" action="show" /> 

inside a .gsp file and it will work nicely.

But also I'd like to use the same closure createLink inside a .groovy file which is not part of the grails views

4条回答
放荡不羁爱自由
2楼-- · 2019-01-17 22:15

For unmanaged classes you can reference the g taglib with:

def g = ApplicationHolder.application.mainContext.getBean('org.codehaus.groovy.grails.plugins.web.taglib.ApplicationTagLib')
查看更多
Bombasti
3楼-- · 2019-01-17 22:18

The native way to do this as of Grails 2.0 outside of controllers (so for services, async jobs, etc) is to use the LinkGenerator class. Works everywhere and mentioned in the official docs. See example here

http://mrhaki.blogspot.ca/2012/01/grails-goodness-generate-links-outside.html

查看更多
欢心
4楼-- · 2019-01-17 22:23

You can use taglib methods from Grails controllers, for example:

def userShow = g.createLink(controller:"user", action:"show")

For builtin taglibs (or those in the g namespace) you can omit the namespace prefix in the method call.

查看更多
我命由我不由天
5楼-- · 2019-01-17 22:26

Inject the grailsApplication into your service/filter.

def grailsApplication

And get the Spring bean.

def g = grailsApplication.mainContext.getBean('org.codehaus.groovy.grails.plugins.web.taglib.ApplicationTagLib')
def userShow = g.createLink(controller: 'user', action: 'show')
查看更多
登录 后发表回答