6

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静的コンテキストからアクセスしようとしていることです。どうすればこれを回避できますか?

4

2 に答える 2

9

オブジェクトは taglib であり、コントローラーのgようにドメイン クラス内では使用できません。grailsApplicationここに示すように、それを取得できます:ドメインクラスでタグライブラリを関数として呼び出す方法

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
于 2012-06-25T19:21:29.940 に答える
6

Grails 2.x を使用している場合は、LinkGenerator API を使用できます。以下に例を示します。以前にテストしていたドメイン クラスを再利用しているので、URL に関連しない機能は無視してください。

class Parent {
    String pName

    static hasMany = [children:Child]

    static constraints = {
    }
    static transients = ['grailsLinkGenerator']

    static Map options() {
        def linkGen = ContextUtil.getLinkGenerator();
        return ['url':linkGen.link(controller: 'test', action: 'index')]
    }
}

静的メソッドを持つユーティリティ クラス

@Singleton
class ContextUtil implements ApplicationContextAware {
    private ApplicationContext context

    void setApplicationContext(ApplicationContext context) {
        this.context = context
    }

    static LinkGenerator getLinkGenerator() {
        getInstance().context.getBean("grailsLinkGenerator")
    }

}

新しいユーティリティ Bean の Bean 定義

beans = {
    contextUtil(ContextUtil) { bean ->
        bean.factoryMethod = 'getInstance'
    }
}

ベース URL が必要な場合はabsolute:true、link 呼び出しに追加します。

于 2012-06-25T19:19:50.250 に答える