Search code examples
javamustache

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.


Solution

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