How to loop through Map in Thymeleaf

Spring MvcThymeleaf

Spring Mvc Problem Overview


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.

Spring Mvc Solutions


Solution 1 - Spring Mvc

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.

Solution 2 - Spring Mvc

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>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionphil.e.bView Question on Stackoverflow
Solution 1 - Spring Mvcphil.e.bView Answer on Stackoverflow
Solution 2 - Spring MvcACVView Answer on Stackoverflow