简体   繁体   中英

How to iterate over map using mustache in java

I'm newbie to mustache and was wondering how to iterate over HashMap using mustache given this Map

Map mapA = new HashMap();

mapA.put("key1", "element 1");
mapA.put("key2", "element 2");
mapA.put("key3", "element 3");

The map key names vary. Ideally, I want mustache to iterate over both its key and values. So in java it will look like this:

for (Map.Entry<String, Object> entry : mapA.entrySet()) {
   String key = entry.getKey();
   String value = entry.getValue();
   // ...
} 

So can someone tell me how to achieve above in mustache. I mean how would the template looks like? I tried this template but had no luck so far:(

{{#mapA}}
  <li>{{key}}</li>
  <li>{{value}}</li>
{{/mapA>

So when I run this template, the output <li> tags comes out empty, why? Thanks.

I don't know mustache but basing on some samples of code I have seen, I think you should define an entrySet variable in your Java code like this

Set<Map.Entry<String,Object>> entrySet = mapA.entrySet();

and use it instead of mapA in your mustache code

{{#entrySet}}
  <li>{{key}}</li>
  <li>{{value}}</li>
{{/entrySet}}

it is much simpler than that, just do it like this:

{{#mapA}}
  {{#entrySet}}
    <li>{{key}}</li>
    <li>{{value}}</li>
  {{/entrySet}}
{{/mapA}}

As @Dici mentioned above, you can use an entrySet . You do not have to use any special options on the factory and can pass it directly to execute . In your template you can use a top level map if your template is very simple.

Java

Map<String, String> map = new HashMap<>();
map.put("key1", "value1");
map.put("key2", "value2");

Writer writer = new OutputStreamWriter(System.out);
MustacheFactory mustacheFactory = new DefaultMustacheFactory();
Mustache template = mustacheFactory.compile("map.template");
template.execute(writer, map.entrySet()).close();

Mustache Template ( map.template )

{{#.}}
keylabel:{{key}} : valuelabel:{{value}}
{{/.}}

Result

keylabel:key1 : valuelabel:value1
keylabel:key2 : valuelabel:value2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM