Play2.3 自定义模板类型 -- Java 版

在上一篇 Play2 自定义模板类型 (Java&Scala),是基于 Play2.2 怎么自定义 Json 模板类型,分别用 Java 和 Scala 实现。从 Play2.3 开始,模板明确了是用 Twirl,所以构建文件上的配置略有不同,并且模板编译出的源文件位置也不一样,Play2.2 前生成的模板源文件在 target/scala-2.10/src_managed/main/views 目录,现在是生成在 target/twirl/main/views 目录。


在 Play2.3 中仍然是默认只支持 html, txt, xml, js 四种类型的模板,见 SbtTwirl。我们这里还是以增加 Json 模板支持为例,且只介绍用 Java 的方式。因为 Play2 尽管可以用 Java 来编写应用,但实现部份基本是 Scala,所以如果用 Scala 来进行扩展相对来说来比用 Java 简单些。

Play2.3 官方的自定义模板的文档 Adding support for a custom format to the template engine 有些出入,似乎还未来得急更新,以实操为证。

还是从构建文件开始

一: 修改 build.sbt 文件,加上 (你要是愿意用 Build.scala 也无妨):
1import play.twirl.sbt.Import.TwirlKeys
2......
3......
4
5TwirlKeys.templateFormats += ("json" -> "templates.JsonFormat.instance")

play.twirl.sbt.Import.TwirlKeys 下总共有以下六个关于模板的配置项

twirlVersion, templateFormatstemplateImports , useOldParser, sourceEncodingcompileTemplates

二:Json.java
 1package templates;
 2
 3import play.twirl.api.BufferedContent;
 4import scala.collection.immutable.Seq;
 5import scala.collection.immutable.Vector;
 6
 7public class Json extends BufferedContent<Json> {
 8
 9  public Json(String jsonString) {
10    super(Vector.<Json>empty(), jsonString);
11  }
12
13  public Json(Seq<Json> elements) {
14    super(elements, "");
15  }
16
17  public String contentType() {
18    return "application/json";
19  }
20}

需要额外处理通过 Seq<Json> 构造 Json 实例。

三:JsonFormat.java
 1package templates;
 2
 3import play.twirl.api.Format;
 4import scala.collection.immutable.Seq;
 5
 6public class JsonFormat implements Format<Json> {
 7
 8  @Override
 9  public Json raw(String text) {
10    return new Json(text);
11  }
12
13  @Override
14  public Json escape(String text) {
15    return new Json(text);
16  }
17
18  @Override
19  public Json empty() {
20    return new Json("");
21  }
22
23  @Override
24  public Json fill(Seq<Json> elements) {
25    return new Json(elements);
26  }
27
28  public static final JsonFormat instance = new JsonFormat();
29}

现在的 Format 多了两个抽象方法, empty() 和 fill(Seq<Json> elements)

其余怎么写模板文件,怎么在 Controller 中渲染和这里 Play2 自定义模板类型 (Java&Scala) 是一样的。 永久链接 https://yanbin.blog/play2-3-custom-view-template-java/, 来自 隔叶黄莺 Yanbin's Blog
[版权声明] 本文采用 署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0) 进行许可。