gpt4 book ai didi

grails - 无法在网域类别中使用Grails g.link

转载 作者:行者123 更新时间:2023-12-04 13:24:05 24 4
gpt4 key购买 nike

我在返回URL的域类中有静态方法。我需要动态生成该url,但g.link无法正常工作。

static Map options() {
// ...
def url = g.link( controller: "Foo", action: "bar" )
// ...
}

我收到以下错误:
Apparent variable 'g' was found in a static scope but doesn't refer to a local variable, static field or class. Possible causes:
You attempted to reference a variable in the binding or an instance variable from a static context.
You misspelled a classname or statically imported field. Please check the spelling.
You attempted to use a method 'g' but left out brackets in a place not allowed by the grammar.
@ line 17, column 19.
def url = g.link( controller: "Foo", action: "bar" )
^

1 error

显然我的问题是我正在尝试从静态上下文访问 g,那么我该如何解决呢?

最佳答案

g对象是一个标记库,它在域类中不可用,就像在 Controller 中一样。您可以通过grailsApplication来获得它,如下所示:How To Call A Taglib As A Function In A Domain Class

在Grails 2+中执行此操作的更好方法是通过grailsLinkGenerator服务,如下所示:

def grailsLinkGenerator

def someMethod() {
def url = grailsLinkGenerator.link(controller: 'foo', action: 'bar')
}

在这两种情况下,您都需要做一些额外的工作才能从静态上下文中获取 grailsApplication/ grailsLinkGenerator。最好的方法可能是从您的域类的 domainClass属性中获取它:
def grailsApplication = new MyDomain().domainClass.grailsApplication
def grailsLinkGenerator = new MyDomain().domainClass.grailsApplication.mainContext.grailsLinkGenerator

关于grails - 无法在网域类别中使用Grails g.link,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11194169/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com