How to iterate over a list in Thymeleaf

Posted on

The list is most commonly used collection in Java. We often need to send items from a list to a model view that will be displayed in the UI. Thymeleaf is a very popular template engine and Spring Boot provides excellent support for Thymeleaf. This is why Thymeleaf is commonly used with Spring Boot applications.

In this short series of tutorials, we take a look at various aspects of Thymeleaf. In one of our previous articles, we explained how iterate over a map in Thymeleafand here we look at how to iterate through List in Thymeleaf.

If you are a Spring Boot developer or just starting to learn, it might be a good idea to go through the complete guide to Thymeleaf with Spring Boot.

Passing a List to Thymeleaf

First consider a simple example, so we have our fruit list which we want to pass to the Thymeleaf template and display later in the view.

The code below shows how to pass a base channel list in Thymeleaf.

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

fruits.add("Apple");
fruits.add("Orange");
fruits.add("Grapes");
fruits.add("Kiwi");
fruits.add("Guava");

model.addAttribute("fruits",fruits);

Now consider an example where we want to pass a List of objects at Thymeleaf. Here we pass List of employees to the Thymeleaf model.

// below service.getAll() method is returning List of Employee

List<Employee> employees = service.getAll();
model.addAttribute("employees", employees);

In the section below we will see how we iterate through the two lists employees and fruits.

Loop / Iterate through list in Thymeleaf

In our Thymeleaf model, we now have an employees and one fruits listing. Let’s learn how to iterate through the list in Thymeleaf.

First, let’s walk through our simple fruit list:

<ol>
	<li th:each="fruit: ${fruits}"><span th:text="${fruit}"></span></li>
</ol>

It’s simple, we use th:each iterate over a list. Each item of fruits will be assigned to the variable fruit one by one as the iteration progresses. The iteration will take place not times when not is the size of the list.

Now let’s iterate Employees and print it Employee object values:

<table style="border: solid 1px black;">
	<thead>
		<tr>
			<th>ID</th>
			<th>NAME</th>
		</tr>
	</thead>
	<tbody>
		<tr th:each="employee: ${employees}">
			<td th:text="${employee.id}" />
			<td th:text="${employee.name}" />
			</tr>
		</tbody>
	</table>

In the example above, we consider that the employee has two states id and name. The code is quite simple and self-explanatory. We use th:each for iteration then we access identifier, and Last name recovered employee.

Conclusion

In this tutorial, we learned how to loop through a list in Thyemeleaf using two simple examples.

Thanks for reading!

Leave a Reply

Your email address will not be published.