How To Use th:each For Iteration In Thymeleaf Template?

SHARE & COMMENT :

In my previous articles I have explained about the hello world example and the expression language. This tutorial explains how to iterate the list of values from an object. For Iteration In Thymeleaf Template, it provides th:each attribue for using inside a table element to iterate over the list of objects and display the list. This feature also provides iterationStatus context to retrieve the extra details about size of the list, row count, whether that is the first or last element, etc. This feature is very useful for creating the table list with the dynamic values.

1. Set Up Thymeleaf Application

To demonstrate this example, I am using our previous hello world example.Use the same example and replace our code snippet as below. You can use the set up details as mentioned in the hello world example.

2. Create Template with th:each

If you look at the below example, the tamplate has the th:each which is replaced with the dynamic values by the template engine.

employees.xml

<!DOCTYPE html SYSTEM "http://www.thymeleaf.org/dtd/xhtml1-strict-thymeleaf-4.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
	xmlns:th="http://www.thymeleaf.org">
<head>
<title>Iteration in Thymeleaf Template Engine!!</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<h1>Employees</h1>
    <table>
      <tr>
      	<th>SNO</th>
      	<th>ID</th>
        <th>NAME</th>
        <th>CITY</th>
        <th>COUNTRY</th>
      </tr>
      <tr th:each="emp,iterationStatus  : ${employees}">
      	<td th:text="${iterationStatus.count}">1</td>
        <td th:text="${emp.id}">001</td>
        <td th:text="${emp.name}">Name</td>
        <td th:text="${emp.city}">City</td>
        <td th:text="${emp.country}">Country</td>
      </tr>
    </table>
</body>
</html>

</body>
</html>

3. Create Bean Employee

Employee.java

package javabeat.net.thymeleaf;

public class Employee {
	private String id;
	private String name;
	private String city;
	private String country;
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getCity() {
		return city;
	}
	public void setCity(String city) {
		this.city = city;
	}
	public String getCountry() {
		return country;
	}
	public void setCountry(String country) {
		this.country = country;
	}
}

4. Create Servlet with Thymeleaf Context and Attach Template

ThymeleafIterationExample.java

package javabeat.net.thymeleaf;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.TreeSet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.WebContext;
import org.thymeleaf.templateresolver.ServletContextTemplateResolver;

public class ThymeleafIterationExample extends HttpServlet{
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
    	ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver();
        // XHTML is the default mode, but we will set it anyway for better understanding of code
        templateResolver.setTemplateMode("XHTML");
        templateResolver.setPrefix("/WEB-INF/");
        templateResolver.setSuffix(".html");
        templateResolver.setCacheTTLMs(3600000L);
        TemplateEngine templateEngine = new TemplateEngine();
        templateEngine.setTemplateResolver(templateResolver);
        WebContext ctx = new WebContext(req, resp, getServletConfig().getServletContext(), req.getLocale());
        ArrayList<Employee> employees = new ArrayList<Employee>();
        Employee employee = new Employee();
        employee.setId("001");
        employee.setName("Rahul");
        employee.setCity("Bangalore");
        employee.setCountry("India");
        employees.add(employee);
        employee = new Employee();
        employee.setId("002");
        employee.setName("Deepan");
        employee.setCity("Namakkal");
        employee.setCountry("India");
        employees.add(employee);
        employee = new Employee();
        employee.setId("003");
        employee.setName("Ashwanth");
        employee.setCity("Bangalore");
        employee.setCountry("India");
        employees.add(employee);

        // This will be prefixed with /WEB-INF/ and suffixed with .html
        ctx.setVariable("employees", employees);
        templateEngine.process("employees", ctx, resp.getWriter());

        resp.setContentType("text/html;charset=UTF-8");
        resp.setHeader("Pragma", "no-cache");
        resp.setHeader("Cache-Control", "no-cache");
        resp.setDateHeader("Expires", 1000);
	}
}

5. Run The Thymeleaf Application

If you execute the above code, you would see the below output as below.

iteration-thymeleaf

Comments

comments

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Speak Your Mind

*

Close
Please support the site
By clicking any of these buttons you help our site to get better