How to Iterate over a List in Thymeleaf

The List is the most commonly used collection in Java. We often need to send the items in a list to a view template that will be displayed in the User Interface. Thymeleaf is a very popular template engine and Spring Boot provides great support to Thymeleaf. This is the reason, Thymeleaf is used commonly with Spring Boot applications.

In this short tutorial series, we are looking at various aspects of Thymeleaf. In one of our previous articles, we explained how to iterate over a Map in Thymeleaf, and here we are looking at how to loop through List in Thymeleaf.

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

Passing a List to Thymeleaf

Let’s consider a simple example first, so we have our list of fruits that we want to pass to the Thymeleaf template and later display in the view.

The code snipped below shows how to pass a basic list of strings 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 to the Thymeleaf. Here, we are passing List of Employee to the Thymeleaf template.

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

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

In the below section, we will look at how we iterate over both list employees and fruits.

Loop / Iterate through List in Thymeleaf

In our Thymeleaf template, now we have one employees and a fruits list. Let’s learn how to iterate over the list in Thymeleaf.

First, we will loop through our simple list of fruits:

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

It’s simple, we are using th:each to iterate over a list. Each item from fruits will be assigned to variable fruit one by one as iteration goes on. The iteration will happen n times where n is the size of list.

Now Let’s iterate Employees and print the Employee object’s 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 above example, we are considering employee has two states id, and name. The code is pretty simple and self-explanatory. We are using th:each for iteration then we are accessing id, and name from the fetched employee.

Conclusion

In this tutorial, we have learned how to iterate over a List in Thyemeleaf using two simple examples.

Thanks for Reading!

Newsletter Updates

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

Leave a Reply