How one can Loop by means of Map in Thymeleaf


Thymeleaf is a very fashionable template engine. It’s extensively used with Spring Boot purposes. We will simply cross information from the controller to Thymeleaf templates and vice versa.

In java, Collections are the preferred solution to retailer information. So after we develop the Spring Boot software, Java Collections is certainly used no less than as soon as.

So on this brief tutorial collection, we are going to have a look at easy methods to loop by means of Assortment in Thymeleaf and we’re beginning with Maps. So this text will clarify, easy methods to iterate over a map within the Thymeleaf template. We additionally lately wrote a whole tutorial on Thymeleaf with Spring Boot so if you wish to dig deeper, check out it.

Let’s get began:

Passing Map to the Thymeleaf template

Let’s take into account a easy instance of a Pupil scorecard. We are going to retailer the scholar roll no as a key and rating as the worth within the HashMap.

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

// service.getAllStudents() is returning the checklist of scholars
for(Pupil scholar : service.getAllStudents()) 
    map.put(scholar.getRollNo(), scholar.getScore());


Now this studentScoreCard mannequin attribute will likely be obtainable within the Thymeleaf template. So transfer to the subsequent part and iterate and print these values.

Iterating over a Map in Thymeleaf

From the above part, we acquired our studentScoreCard map in our Thymeleaf template which is our HTML web page.

To iterate over a Map on this case the HashMap implementation of Map, we are going to use th:every. It’s used for iteration over any assortment.

<desk fashion="border: stable 1px black;">
            <th>Roll No.</th>
		<tr th:every="scholar: ${studentScoreCard}">
		    <td th:textual content="$" />
		    <td th:textual content="$" />

We will use key and worth on the map to fetch the important thing and worth respectively.


On this tutorial, we realized easy methods to iterate over a Map and show its key and worth within the Person Interface by looping utilizing th:every.

Thanks for Studying!



Leave a Comment