Chunk http://www.x5software.com/chunk/对 json 友好。 JSON 可以用作控制器代码中的标记值或用于执行/宏调用的模板本身。
{% exec %}
{% data @json %}
{ name: "whatever",
vitals: ["an","array","of","data"],
friends: [{name: "bob"},{name: "crystal"}]
}
{% enddata %}
<div>Name: {$name}</div>
{% if ($friends) %}
<div>Friends:
<ul>
{% loop in $friends as $friend %}
<li>{$friend.name}</li>
{% endloop %}
</ul>
</div>
{% endif %}
{% endexec %}
或者,只需使用内部模板并从 java 端注入 json。
src/主题/example.chtml
<div>Name: {$name}</div>
{% if ($friends) %}
<div>Friends:
<ul>
{% loop in $friends as $friend %}
<li>{$friend.name}</li>
{% endloop %}
</ul>
</div>
{% endif %}
MyController.java
Theme theme = new Theme();
Chunk html = theme.makeChunk("example");
html.set("name", "whatever");
html.set("vitals", getJsonArray() );
html.set("friends", getJsonFriendObjects() );
html.render( out );
只要 getJsonXXX() 方法返回实现 List 和 Map 的内容,Chunk 就会将其正确粘合到模板中(即使这些 List 和 Map 嵌套更多 List 和 Map)。
Output:
<div>Name: whatever</div>
<div>Friends:
<ul>
<li>bob</li>
<li>crystal</li>
</ul>
</div>