How to browse the map in Thymeleaf

Posted on

Thymeleaf is a very popular template engine. It is widely used with Spring Boot applications. We can easily pass data from controller to Thymeleaf models 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’ll look at how to browse Collection in Thymeleaf and we’ll start with Maps. This article therefore explains how to iterate over a map in the Thymeleaf model. We also recently wrote a full tutorial on Thyme leaf with spring bunch so if you want to dig deeper, check it out.

Let’s start:

Pass the map to the Thymeleaf template

Let’s take a simple example of Student score card. We will store the list of students no as a key and mark 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 The model attribute will be available in the Thymeleaf template. So move on to the next section, browse and print these values.

Iterate 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 retrieve 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 looping UI using th: each.

Thanks for reading!

Leave a Reply

Your email address will not be published.