Loop in java handlebar template along with other parameters

951 Views Asked by At

I want to create a handlebar java template something like:

"This is a sample template with {{parameter1}} {{#if object_list}} {{#each object_list}} {{object_list.somevar}} {{object_list.othervar}} {{/each}}{{/if}}"

Before I could do object_list.something, I am not even able to do a simple loop. I tried the following:

Map<String, String> map = new HashMap<String, String>();
    map.put("people", "[ Yehuda Katz, Alan Johnson, Charles Jolley ]");
    map.put("k2", "v2");

        System.out.println("Map: "
            + handlebars.compileInline("{{#each people}} {{@index}}:{{this}}  \n {{/each}}")
            .apply(map));               
}

and it gives:

Map:  :[B@6cd8737  
  :false  

Any pointers on how to achieve this? Note: These parameters will be received in a json file, so I cannot(or will prefer not to) create list of objects actually.

I am following: https://github.com/jknack/handlebars.java

1

There are 1 best solutions below

1
On BEST ANSWER

Could do it with base mustache. Works as expected. Following is an example:

 private static void test2() throws IOException {
       HashMap<String, Object> scopes = new HashMap<String, Object>();
        scopes.put("name", "Mustache");

        List<String> features = new ArrayList<String>();
        features.add("f1");
        features.add("f2");

        scopes.put("features", features);

        List<Map<String, String>> discounts = new ArrayList<Map<String,String>>();
        Map<String, String> discount1 = new HashMap<String, String>();
        Map<String, String> discount2 = new HashMap<String, String>();
        discount1.put("type", "a");
        discount1.put("value", "15");

        discount2.put("type", "b");
        discount2.put("value", "215");

        discounts.add(discount1);
        discounts.add(discount2);

        scopes.put("discounts", discounts);

        Writer writer = new OutputStreamWriter(System.out);
        MustacheFactory mf = new DefaultMustacheFactory();
        Mustache mustache = mf.compile(new StringReader("{{name}},  {{#features}} Feature: {{.}}  {{/features}}! {{#discounts}} {{type}} {{value}}{{/discounts}}"), "example");
        mustache.execute(writer, scopes);
        writer.flush(); 
 }