• Menu
  • Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

JavaBeat

Java Tutorial Blog

  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)
  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)

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

November 27, 2013 //  by Krishna Srinivasan//  Leave a 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

Category: Web FrameworksTag: template engine, Thymeleaf

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.

Previous Post: « How To Set Attributes in Thymeleaf Template using th:attr?
Next Post: How To Use Switch Statement (th:switch) In Thymeleaf Template? »

Reader Interactions

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Primary Sidebar

Follow Us

  • Facebook
  • Pinterest

FEATURED TUTORIALS

New Features in Spring Boot 1.4

Difference Between @RequestParam and @PathVariable in Spring MVC

What is new in Java 6.0 Collections API?

The Java 6.0 Compiler API

Introductiion to Jakarta Struts

What’s new in Struts 2.0? – Struts 2.0 Framework

JavaBeat

Copyright © by JavaBeat · All rights reserved
Privacy Policy | Contact