在java车把模板中循环以及其他参数

时间:2016-12-19 19:26:54

标签: mustache handlebars.java

我想创建一个类似于:

的车把java模板
"This is a sample template with {{parameter1}} {{#if object_list}} {{#each object_list}} {{object_list.somevar}} {{object_list.othervar}} {{/each}}{{/if}}"

在我能做object_list.something之前,我甚至无法做一个简单的循环。我尝试了以下方法:

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

它给出了:

Map:  :[B@6cd8737  
  :false  

关于如何实现这一点的任何指针?   注意:这些参数将在json文件中接收,因此我不能(或者不愿意)实际创建对象列表。

我关注:https://github.com/jknack/handlebars.java

1 个答案:

答案 0 :(得分:0)

可以用基本胡子做到这一点。按预期工作。以下是一个例子:

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