4

Play Framework 1.2.4コントローラーでは、ブラウザーに出力する前に、テンプレートまたはタグのコンテンツを文字列として取得することはできますか?

私はこれができるようになりたいです:

String json = renderAsString("/path/to/template.json", var1, var2);

//then use json as the body of a Play.WS request body.
4

2 に答える 2

3

解決策は、PlayFramework 1.x について話しているという前提に基づいています。

Groovy テンプレート エンジンを使用している場合:

Map<String, Object> args = ...
Template template = TemplateLoader.load("path/to/template.suffix");
String s = template.render(args);

また、 Rythm テンプレート エンジンを使用している場合は、ショートカットの方法があります。

String s = Rythm.render("path/to/template.suffix", param1, param3...);

または、名前付き引数を使用することもできます:

Map<String, Object> args = ...
String s = Rythm.render("path/to/template.suffix", args);

app/rythmテンプレートファイルがフォルダーの下にある場合、Groovy の方法は Rythm でも機能することに注意してください。

于 2012-05-02T02:14:22.387 に答える
0

緑の答えに加えて

json を作成したい場合は、Groovy テンプレートを使用して独自の文字列を作成するよりも、gson を使用することをお勧めします。Gson は Play Framework 1.2.X に含まれています。

詳細については、こちらをご覧ください。Gson doc の例:

class BagOfPrimitives {
    private int value1 = 1;
    private String value2 = "abc";
    BagOfPrimitives() {
        // no-args constructor
    }
}


BagOfPrimitives obj = new BagOfPrimitives();
Gson gson = new Gson();
String json = gson.toJson(obj);  
//json is {"value1":1,"value2":"abc"}

gson の代わりに Flexjson を使用することもできます。

于 2012-05-17T10:22:46.377 に答える