72

I am trying to understand how to loop through all entries in a Map in Thymeleaf. I have a domain object being processed by Thymeleaf that contains a Map.

How do I loop through the keys and fetch the values ?

Thanks.

phil.e.b
  • 2,491
  • 2
  • 16
  • 17

2 Answers2

148

Nevermind... I found it...

<tr th:each="instance : ${analysis.instanceMap}">
    <td th:text="${instance.key}">keyvalue</td>
    <td th:text="${instance.value.numOfData}">num</td>
</tr>

Thanks.

Mahozad
  • 18,032
  • 13
  • 118
  • 133
phil.e.b
  • 2,491
  • 2
  • 16
  • 17
  • 2
    What was the source for this? – Clay Banks Dec 10 '15 at 18:33
  • 5
    ["When iterating maps, iter variables will be of class java.util.Map.Entry."](http://www.thymeleaf.org/doc/tutorials/2.1/usingthymeleaf.html#iterable-values) – ben3000 Jan 26 '17 at 07:20
  • Out of curiosity, is there a way to do this for any object under Java 8 or 9? Just like iterating over objects in JavaScript and JSON, I would think there be a way to take a serializable object of type Foo and do
    If this can't be done, can this become part of Java 10 or the next major version of thymeleaf? This would solve so many headaches and reduce a lot of performance overhead turning entity objects into maps before running them through template engines.
    – patrickjp93 Jan 06 '18 at 02:23
57

In case you have a List as the value. For example, when you have a map with key being the category, and value being a list of items pertaining to that category, you can use this:

<table>
    <tr th:each="element : ${catsAndItems}">
        <td th:text="${element.key}">keyvalue</td>
        <table>
            <tr th:each="anews : ${element.value}">
                <td th:text="${anews.title}">Some name</td>
                <td th:text="${anews.description}">Some name</td>
                <td th:text="${anews.url}">Some name</td>
                <td th:text="${anews.logo}">Some name</td>
                <td th:text="${anews.collectionDate}">Some name</td>
            </tr>
        </table>
    </tr>
</table>
Mahozad
  • 18,032
  • 13
  • 118
  • 133
ACV
  • 9,964
  • 5
  • 76
  • 81