How to Loop through Map in Thymeleaf

Thymeleaf is a very popular template engine. It is widely used with Spring Boot applications. We can easily pass data from the controller to Thymeleaf templates and vice versa.

In java, Collections are the most popular way to store data. So when we develop the Spring Boot application, Java Collections is definitely used at least once.

So in this short tutorial series, we will look at how to loop through Collection in Thymeleaf and we are starting with Maps. So this article will explain, how to iterate over a map in the Thymeleaf template. We also recently wrote a complete tutorial on Thymeleaf with Spring Boot so if you want to dig deeper, take a look at it.

Let’s get started:

Passing Map to the Thymeleaf template

Let’s consider a simple example of a Student scorecard. We will store the student roll no as a key and score as the value in the HashMap.

Map<Integer,Integer> map = new HashMap<>();

// service.getAllStudents() is returning the list of students
for(Student student : service.getAllStudents()) {
    map.put(student.getRollNo(), student.getScore());
}

model.addAttribute("studentScoreCard",map);

Now this studentScoreCard model attribute will be available in the Thymeleaf template. So move to the next section and iterate and print these values.

Iterating over a Map in Thymeleaf

From the above section, we got our studentScoreCard map in our Thymeleaf template which is our HTML page.

To iterate over a Map in this case the HashMap implementation of Map, we will use th:each. It is used for iteration over any collection.

<table style="border: solid 1px black;">
    <thead>
        <tr>
            <th>Roll No.</th>
		    <th>Score</th>
	    </tr>
	</thead>
	<tbody>
		<tr th:each="student: ${studentScoreCard}">
		    <td th:text="${student.key}" />
		    <td th:text="${student.value}" />
		</tr>
	</tbody>
</table>

We can use key and value on the map to fetch the key and value respectively.

Conclusion

In this tutorial, we learned how to iterate over a Map and display its key and value in the User Interface by looping using th:each.

Thanks for Reading!

Newsletter Updates

Enter your name and email address below to subscribe to our newsletter

Leave a Reply