Spring Boot Thymeleaf for each with Example





Hey guys in this post, we will discuss iterating list using each in Thymeleaf with an example.

Overview


Thymeleaf is a Java XML/XHTML/HTML5 template engine that can work both in web and non-web environments. It is better suited for serving XHTML/HTML5 at the view layer of MVC-based web applications, but it can process any XML file even in offline environments. It provides full Spring Framework integration.

Below is the example to iterate the list in Thymeleaf –

<tbody>
	<tr th:each="todo: ${todos}">
		<td th:text="${todo.title}"></td>
		<td th:text="${todo.description}"></td>
		<td th:text="${todo.isCompleted}"></td>
	</tr>
</tbody>

Here th:each is the Thymeleaf for each syntax, ${todos} is the list added to the model, todo is the reference variable, each time loop runs, variable todo gets intilaized and we can access the todo properties.

Create spring boot project


There are many different ways to create a spring boot application, you can follow the below articles to create one –

>> Create spring boot application using Spring initializer
>> Create spring boot application in Spring tool suite [STS]
>> Create spring boot application in IntelliJ IDEA

Add maven dependencies


Open pom.xml and add the following dependencies –

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.4.4</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>in.bushansirgur</groupId>
	<artifactId>springboot-thymeleaf</artifactId>
	<version>v1</version>
	<name>springboot-thymeleaf</name>
	<description>Spring boot thymeleaf</description>
	<properties>
		<java.version>1.8</java.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-thymeleaf</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-devtools</artifactId>
			<scope>runtime</scope>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>

spring-boot-starter-web dependency for building web applications using Spring MVC. It uses the tomcat as the default embedded container. We have added the spring-boot-starter-thymeleafdependency for Thymeleaf support. We have also added the spring-boot-devtools dependency for automatic reloads or live reload of applications.



Create a model class


Create Todo.java inside the in.bushansirgur.springboot.model package and add the following content

package in.bushansirgur.springboot.model;

public class Todo {
	
	private String title;
	
	private String description;
	
	private boolean isCompleted;

	public Todo(String title, String description, boolean isCompleted) {
		super();
		this.title = title;
		this.description = description;
		this.isCompleted = isCompleted;
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public String getDescription() {
		return description;
	}

	public void setDescription(String description) {
		this.description = description;
	}

	public boolean isCompleted() {
		return isCompleted;
	}

	public void setCompleted(boolean isCompleted) {
		this.isCompleted = isCompleted;
	}

	
}

This is just a POJO that contains the private fields, setters, and getters.

Create a controller


Create HomeController.java inside the in.bushansirgur.springboot.controller package and add the following content

package in.bushansirgur.springboot.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.servlet.ModelAndView;

import in.bushansirgur.springboot.model.Todo;

@Controller
public class HomeController {
	
	@GetMapping("/todos")
	public ModelAndView getCurrentAndTime() {
		ModelAndView mav = new ModelAndView("home");
		List<Todo> list = new ArrayList<Todo>();
		list.add(new Todo("Learn spring security", "some description", false));
		list.add(new Todo("Prepare lunch", "some description", true));
		list.add(new Todo("Learn php", "some description", false));
		list.add(new Todo("Bring medicine", "some description", true));
		mav.addObject("todos", list);
		return mav;
	}
}

We have created the handler method getTodos(), which will return the ModelAndView. Model contains the list of todos and View contains the name of the template home.

Create a view


Inside the templates folder, create home.html file and add the following content

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" 
		integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l" 
		crossorigin="anonymous">
</head>
<body>
	<div class="container">
		<table class="table table-bordered">
			<thead>
				<tr>
					<th>Todo</th>
					<th>Description</th>
					<th>isCompleted?</th>
				</tr>
			</thead>
			<tbody>
				<tr th:each="todo: ${todos}">
					<td th:text="${todo.title}"></td>
					<td th:text="${todo.description}"></td>
					<td th:text="${todo.isCompleted}"></td>
				</tr>
			</tbody>
		</table>
	</div>
</body>
</html>

Here inside the <tbody>, we are looping the <tr> with Thymeleaf th:each. We are accessing the list using ${todos} and printing the todo properties using th:text.

Run the app


Run the application using the below maven command –

mvn spring-boot:run

Open the browser and enter the following URL – http://localhost:8080/todos

Screenshot-2021-04-21-at-3-52-02-PM



Bushan Sirgur

Hey guys, I am Bushan Sirgur from Banglore, India. Currently, I am working as an Associate project in an IT company.

Leave a Reply