在Java Mustache中为Template添加格式化函数



我有一个Java Mustache应用程序,我需要应用一个函数以货币格式呈现它

我有我的模板

{{#currency}}{{number_to_format}}{{/currency}}

我的功能

HashMap<String, Object> scopes = new HashMap<String, Object>();
//Add date 
scopes.put("number_to_format",BigDecimal.ONE);
scopes.put("currency", new TemplateFunction() {
public String apply(String input) {
NumberFormat currency = NumberFormat.getCurrencyInstance();
return currency.format(new BigDecimal(input));                          

}
}
);
MustacheFactory mf = new DefaultMustacheFactory();
Mustache mustache = mf.compile("template.mustache");
mustache.execute(writer,scopes).flush();

我无法获得";输入";变量,我总是得到变量名"number_to_format";。如果我在函数中返回一个值,它将被渲染。

如何在输入中获得我的vaible的数值?

输入变量是一个传入模板,您需要对其进行渲染以获得值
因此,使用相同的工厂和范围再次渲染它并获得值

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

否则,删除";{{〃和{}〃}〃;并将其用作散列映射的密钥

最新更新