mustache 模板引擎

mustache 模板只包含标签,不包含逻辑(比如,if-else 语句、for 循环)。

标签是用双花括号表示,比如:{{person}}, {{#person}},下面介绍不同类型的标签。

Variables

变量 {{name}} 是最基础的标签,它会在当前上下文查找键为 name 的值。如果没有找到,则递归地在父上下文查找,缺失则返回空字符串。

所有变量默认都会进行 HTML 转义,如果想禁止转义,可以使用 {{{name}}}{{&name}}

Sections

Sections 会将文本渲染一次或多次。

Sections 由 {{#person}} 开始, {{/person}} 结束。

  • 如果 person 不存在,或是 false 或空列表,则块中的 HTML 不会被渲染
  • 如果 person 是一个列表,则列表中的元素都会被渲染
  • 如果 person 是一个非 false 的值,则该值会被渲染一次

Inverted Sections

Inverted Sections 由 {{^person}} 开始,{{/person}} 结束。

如果 person 不存在,或是 false 或空列表,则块中的 HTML 会被渲染。

注释

注释 {{! ignore me }}

Partials

Partials {{> user}} 会将 user.mustache 模板的内容渲染到当前位置。

Set Delimiter

Set Delimiter 可以重新定义标签。

  • {{=<% %>=}} 将标签重定义成 <% name %>
  • <%={{ }}=%> 将标签恢复成默认样式 {{ name }}

jmustache 模板引擎

<!-- https://mvnrepository.com/artifact/com.samskivert/jmustache -->
<dependency>
<groupId>com.samskivert</groupId>
<artifactId>jmustache</artifactId>
<version>1.15</version>
</dependency>
String text = "One, two, {{three}}. Three sir!";
Map<String, String> data = new HashMap<String, String>();
data.put("three", "five");
Template tmpl = Mustache.compiler().compile(text);
System.out.println(tmpl.execute(data));
// result: "One, two, five. Three sir!"
void executeTemplate (Reader template, Writer out, Map<String, String> data) {
Mustache.compiler().compile(template).execute(data, out);
}

参阅

posted @   廖子博  阅读(341)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示