gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 05:34:03 54 4
gpt4 key购买 nike

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

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

我想要“宠物”和“玩具”

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

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

最佳答案

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>

关于java - 如何使用 jmustache 库获取模板参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56962577/

54 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com