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

How to fetch template parameters using jmustache library?

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

The {{pet}} chased after the {{toy}}

我想要 "pet" 和 "toy"

我只能使用 samskivert/jmustache library 所以我不能使用不同的小胡子库。

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

实际上有一种机制可以使用 Visitor 模式 https://github.com/samskivert/jmustache/issues/108#issuecomment-510071602 but it's not released yet https://github.com/samskivert/jmustache/issues/109#issue-466358322

Mustache.Visitor Used to visit the tags in a template without executing it

示例:

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; }
});

Visitor 可从 jmustache 版本 1.15:

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