0

我想创建一个车把 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

4

1 回答 1

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(); 
 }
于 2016-12-20T05:15:24.450 回答