如何解决将格式化功能添加到Java Mustache中的模板
我有一个Java Mustache应用,我需要应用一个函数以货币格式呈现它
我有我的模板
"go.languageServerExperimentalFeatures": {
"diagnostics": true,"documentLink": true
},"go.liveErrors": {
"enabled": true,"delay": 500,},
还有我的功能
{{#currency}}{{number_to_format}}{{/currency}}
我无法获得“输入”变量中的值,我总是获得变量名称“ number_to_format”。如果我在函数中返回一个值,它将被呈现。
如何在输入中获取我的副总裁的数值?
解决方法
输入变量是一个传入模板,您需要对其进行渲染以获取值
因此,再次使用相同的工厂和范围对其进行渲染并获得值
HashMap<String,Object> scopes = new HashMap<String,Object>();
final MustacheFactory mf = new DefaultMustacheFactory();
// Add date
scopes.put("number_to_format",BigDecimal.ONE);
scopes.put("currency",new TemplateFunction() {
public String apply(String input) {
//render the input as template to get the value
Mustache mustache = mf.compile(new StringReader(input),"");
StringWriter out = new StringWriter();
mustache.execute(out,scopes);
NumberFormat currency = NumberFormat.getCurrencyInstance(Locale.US);
return currency.format(new BigDecimal(out.toString()));
}
});
Mustache mustache = mf.compile("template.mustache");
mustache.execute(new PrintWriter(System.out),scopes).flush();
否则,通过检查输入从HashMap中获取值
if(input.equals("{{number_to_format}}")){
input = scopes.get("number_to_format").toString();
}
NumberFormat currency = NumberFormat.getCurrencyInstance(Locale.US);
return currency.format(new BigDecimal(input));
否则,请删除“ {{”和“}}”,并将其用作哈希映射的键
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。