如何使用jmustache库获取模板参数?

时间:2019-07-10 02:16:48

标签: java mustache

我正在尝试获取所有模板参数-{{}}中的参数名称。例如,对于此模板:

  

在{{toy}}之后追逐的{{pet}}

我想得到“宠物”和“玩具”

我只能使用samskivert/jmustache library,所以不能使用其他的胡子库。

有没有办法用jmustache做到这一点,这样我就不必用正则表达式解析字符串了?

2 个答案:

答案 0 :(得分:1)

Mustache.Visitor用于在不执行模板的情况下访问模板中的标签

示例:

List<String> vars = new ArrayList<>();
Template tmpl = ... // compile your template
tmpl.visit(new Mustache.Visitor() {

  // I assume you don't care about the raw text or include directives
  public void visitText(String text) {}

  // You do care about variables, per your example
  public void visitVariable(String name) {vars.add("Variable: " + name); }

  // Also makes sense to visit nested templates.
  public boolean visitInclude(String name) { vars.add("Include: " + name); return true; }

  // I assume you also care about sections and inverted sections
  public boolean visitSection(String name) { vars.add("Section: " + name); return true; }

  public boolean visitInvertedSection(String name) { vars.add("Inverted Section: " + name); return true; }
});

Visitorjmustache版本1.15开始可用:

<groupId>com.samskivert</groupId>
<artifactId>jmustache</artifactId>
<version>1.15</version>

答案 1 :(得分:0)