首页 > 解决方案 > 在 Java Mustache 中为模板添加格式化功能

问题描述

我有一个 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”。如果我在函数中返回一个值,它将被渲染。

如何获得输入变量的数值?

标签: javatemplatesnumber-formattingmustache

解决方案


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

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

否则删除 "{{" 和 "}}" 并将其用作 hashmap 的键


推荐阅读