Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate over map using mustache in java

Tags:

java

mustache

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.

like image 909
Simple-Solution Avatar asked Oct 19 '14 15:10

Simple-Solution


People also ask

How do you iterate over mustache list?

Mustache Sections and Iterations Let's now have a look at how to list the todos. For iterating over a list data, we make use of Mustache sections. A section is a block of code which is repeated one or more times depending on the value of the key in the current context.

How to iterate over keys or values in map in Java?

Iterating over keys or values using keySet () and values () methods Map.keySet () method returns a Set view of the keys contained in this map and Map.values () method returns a collection-view of the values contained in this map. So If you need only keys or values from the map, you can iterate over keySet or values using for-each loops.

How to iterate through a map using the three methods?

Before we iterate through a map using the three methods, let's understand what these methods do: entrySet () – returns a collection-view of the map, whose elements are from the Map.Entry class. The entry.getKey () method returns the key, and entry.getValue () returns the corresponding value Next, let's see these methods in action. 3.

What is Mustache template in Java?

Overview In this article, we'll focus on Mustache templates and use one of its Java APIs for producing dynamic HTML content. Mustache is a logicless template engine for creating dynamic content like HTML, configuration files among other things. 2. Introduction


1 Answers

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}}
like image 105
Dici Avatar answered Sep 20 '22 11:09

Dici