Search code examples
javatemplatesnumber-formattingmustache

Add formating function to Template in Java Mustache


I have a Java Mustache app and I need to apply a function to render it in currency format

I have my template

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

And my function

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

I am unable to get the value in the "input" variable, i always get the variable name "number_to_format". If I return a value in the function it will be rendered.

How can i get the numeric value of my vairable in input?


Solution

  • The input variable is an incoming template, you need to render it to get the value
    Therefore again render it with same factory and scopes and get the value

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

    Otherwise get the value from HashMap by checking the input

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

    Otherwise remove the "{{" and "}}" and use it as a key to hashmap