1

Grails ユーザー ガイドに記載されている内容から、コンテンツ ネゴシエーションに基づいてさまざまなコンテンツ形式を送信するための推奨される方法withFormatは、ブロックを使用することです。

import grails.converters.XML
class BookController {

    def list() {
        def books = Book.list()
        withFormat {
            html bookList: books
            js { render "alert('hello')" }
            xml { render books as XML }
        }
    }
}

ただし、これを行うには、すべてのコントローラーメソッドの応答が必要です。withFormatコンテンツを返すすべてのアクションの最後にブロックを単にコピーして貼り付けるよりも、この動作を取得するためのより良い方法はありますか?

4

2 に答える 2

1

最初に頭に浮かんだのは、Interceptor と Filters の 2 つです。

http://grails.org/doc/1.3.7/ref/Controllers/afterInterceptor.html

http://grails.org/doc/latest/guide/6.%20The%20Web%20Layer.html#6.6フィルタ

withFormat を実行できないため、インターセプターは機能しません。それはよりグローバルであるため、残念です。

フィルターはコントローラーごとに機能しますが、少なくともそのレベルでの重複を最小限に抑えることができます.

def afterInterceptor = {model, modelAndView ->
    withFormat {
        html { model }
        js { render "alert('hello')" }
        xml { render model as XML }
    }
}

これは私のテストプロジェクトでうまくいきました。私はそのクロージャーを独自のクラスに入れ、クラスを混ぜ合わせて、よりグローバルなソリューションを実行できるようにしました...ただし、サイコロはありません。

たぶん、すべての afterInterseptors がモデルの modelAndView を共通のクラスに渡すようにしますか? それはうまくいくようです:)(答えながら答えに向けて取り組んでいます)

@Mixin(AfterInterceptorWithFormat)
class FirstController {

    def action1 = {}
    def action2 = {}

    def afterInterceptor = {model, modelAndView ->
        performAfterInterceptor(model, modelAndView)
    }
}

class AfterInterceptorWithFormat {

    def performAfterInterceptor(model, modelAndView) {
        withFormat {
            html { model }
            js { render "alert('hello')" }
            xml { render model as XML }
        }
    }
}

それを試して、あなたの考えを教えてください。

于 2011-12-15T17:36:54.543 に答える
0

What I ended up doing is to simply adjust the default CRUD templates to have the withFormat block at the end of each method.

I realized that what I really wanted was just content-negotiated CRUD, so putting the code into the templates was all I needed for that.

The rest of the controllers for the non-crud parts of my application did not need no-html output, so I didn't need content negotiation on anything but the crud controllers.

于 2012-01-30T14:24:32.747 に答える