How to iterate over map using mustache in java

Simple-Solution picture Simple-Solution · Oct 19, 2014 · Viewed 11.4k times · Source

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.

Answer

Dici picture Dici · Oct 19, 2014

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