How one can Iterate over a Checklist in Thymeleaf


The Checklist is essentially the most generally used assortment in Java. We regularly have to ship the objects in an inventory to a view template that will likely be displayed within the Consumer Interface. Thymeleaf is a very fashionable template engine and Spring Boot supplies nice help to Thymeleaf. That is the explanation, Thymeleaf is used generally with Spring Boot functions.

On this brief tutorial collection, we’re varied elements of Thymeleaf. In one among our earlier articles, we defined tips on how to iterate over a Map in Thymeleaf, and right here we’re tips on how to loop by means of Checklist in Thymeleaf.

If you’re a Spring Boot developer or you’re simply beginning to be taught, it is perhaps a good suggestion to undergo the full information of Thymeleaf with Spring Boot.

Passing a Checklist to Thymeleaf

Let’s take into account a easy instance first, so we now have our checklist of fruits that we need to move to the Thymeleaf template and later show within the view.

The code snipped under reveals tips on how to move a primary checklist of strings in Thymeleaf.

Checklist<String> fruits = new ArrayList<>();



Now, take into account an instance the place we need to move a Checklist of Objects to the Thymeleaf. Right here, we’re passing Checklist of Worker to the Thymeleaf template.

// under service.getAll() technique is returning Checklist of Worker

Checklist<Worker> workers = service.getAll();
mannequin.addAttribute("workers", workers);

Within the under part, we’ll take a look at how we iterate over each checklist workers and fruits.

Loop / Iterate by means of Checklist in Thymeleaf

In our Thymeleaf template, now we now have one workers and a fruits checklist. Let’s discover ways to iterate over the checklist in Thymeleaf.

First, we’ll loop by means of our easy checklist of fruits:

	<li th:every="fruit: ${fruits}"><span th:textual content="${fruit}"></span></li>

It’s easy, we’re utilizing th:every to iterate over an inventory. Every merchandise from fruits will likely be assigned to variable fruit one after the other as iteration goes on. The iteration will occur n instances the place n is the scale of checklist.

Now Let’s iterate Staff and print the Worker object’s values:

<desk model="border: stable 1px black;">
		<tr th:every="worker: $workers">
			<td th:textual content="$worker.id" />
			<td th:textual content="$" />

Within the above instance, we’re contemplating worker has two states id, and identify. The code is fairly easy and self-explanatory. We’re utilizing th:every for iteration then we’re accessing id, and identify from the fetched worker.


On this tutorial, we now have discovered tips on how to iterate over a Checklist in Thyemeleaf utilizing two easy examples.

Thanks for Studying!



Leave a Comment