【问题标题】:Playframework 1.2.4: get the results of render() as a String?Playframework 1.2.4:将 render() 的结果作为字符串获取?
【发布时间】:2012-05-11 12:20:23
【问题描述】:

在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.

【问题讨论】:

    标签: templates playframework playframework-1.x


    【解决方案1】:

    该解决方案基于您在谈论 PlayFramework 1.x 的假设

    如果您使用的是Groovy template engine

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

    如果你使用Rythm template engine,你有一个捷径:

    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。

    【讨论】:

      【解决方案2】:

      除了green answer

      如果您想要创建一个 json,您最好使用 gson,而不是使用 groovy 模板构建您自己的字符串。 Gson 包含在 Play Framework 1.2.X 中。

      您可以找到更多信息here。来自 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。

      【讨论】:

      • 我已经为此使用了 org.codehaus.jackson.map.ObjectMapper。我只是想要一种将 JSON 文件格式显示为模板而不是隐藏在幕后的方法。不确定一个是否比另一个更好,但可能存在性能方面的考虑(但我现在并不真正关心)。
      • 如果你使用groovy做模板,那么它可能比gson或jackson慢,如果你使用rythm或japid,模板方法性能优于gson/jackson,因为它们都是静态编译的java类天生
      猜你喜欢
      • 2016-10-19
      • 1970-01-01
      • 1970-01-01
      • 2013-09-29
      • 1970-01-01
      • 1970-01-01
      • 2022-11-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多