4

在 play framework 1.2.4 Controller 中,是否可以在输出到浏览器之前将模板或标签的内容作为 String 获取?

我希望能够做到这一点:

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 是您想要的,那么您最好使用 gson 而不是使用 groovy 模板构建自己的字符串。Gson 包含在 Play Framework 1.2.X 中。

您可以在此处找到更多信息。来自 Gson 文档的示例:

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"}

您也可以使用 Flexjson 代替 gson。

于 2012-05-17T10:22:46.377 回答