Thymeleaf Iteration Example
April 14, 2023
On this page, we will learn Thymeleaf iteration using th:each in our Java application. The th:each attribute can iterate over following Java objects.
1. Any Array.
2. Any object implementing Java
Map
, Iterable
, Iterator
and Enumeration
.
Find the code snippet to use Thymeleaf th:each.
<tr th:each="writer : ${writers}"> ------ </tr>
Using th:each
Thymeleaf th:each is defined within HTML elements such as <tr>, <td>, <div>, <li> etc.In our example, we are defining th:each within <tr> elements. Here th:each will iterate the object
writers
whose value is assigned by below method.
public static List<Writer> getWriters() { List<Writer> list = new ArrayList<>(); list.add(new Writer(1,"Ram","Ayodhya")); list.add(new Writer(2,"Krishna","Mathura")); list.add(new Writer(3,"Shankar","Varanasi")); list.add(new Writer(4,"Hanuman","Krishkindha")); return list; }
<tr th:each="writer : ${writers}"> <td th:text="${writer.name}">Name</td> <td th:text="${writer.location}">Location</td> <td> <a href="test.html" th:href="@{/profile/writer(id=${writer.id})}">Profile</a> </td> </tr>
writers
object.
<tr> <td>Ram</td> <td>Ayodhya</td> <td> <a href="/cp/profile/writer?id=1">Profile</a> </td> </tr> <tr> <td>Krishna</td> <td>Mathura</td> <td> <a href="/cp/profile/writer?id=2">Profile</a> </td> </tr> <tr> <td>Shankar</td> <td>Varanasi</td> <td> <a href="/cp/profile/writer?id=3">Profile</a> </td> </tr> <tr> <td>Hanuman</td> <td>Krishkindha</td> <td> <a href="/cp/profile/writer?id=3">Profile</a> </td> </tr>
Using Iteration Status Variable
Iteration status variable is defined within th:each. Iteration status is used to keep track of the status of our iteration. It has following properties.index : Current iteration index starting with 0.
count : Current iteration index starting with 1.
size : Total amount of elements.
current : The iteration variable for each iteration.
even/odd : Whether the current iteration is even or odd. These are Boolean properties.
first/last : Whether the current iteration is first or last. These are Boolean properties.
In our code, our variable
itrStat
is working as iteration status variable.
<tr th:each="writer,itrStat : ${writers}" th:class="${itrStat.even}? 'even_css_class':'odd_css_class'"> <td th:text="${itrStat.count}">1</td> <td th:text="${writer.name}">name</td> <td th:text="${writer.location}">location</td> <td th:text="${itrStat.size}">0</td> </tr>
<tr class="odd_css_class"> <td>1</td> <td>Ram</td> <td>Ayodhya</td> <td>4</td> </tr> <tr class="even_css_class"> <td>2</td> <td>Krishna</td> <td>Mathura</td> <td>4</td> </tr> <tr class="odd_css_class"> <td>3</td> <td>Shankar</td> <td>Varanasi</td> <td>4</td> </tr> <tr class="even_css_class"> <td>4</td> <td>Hanuman</td> <td>Krishkindha</td> <td>4</td> </tr>
Complete Example
build.gradledependencies { implementation 'javax.servlet:javax.servlet-api:3.1.0' implementation 'org.thymeleaf:thymeleaf:3.0.0.RELEASE' }
<!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 th:text="#{myblog.title}">Blog Title</title> <link th:href="@{/css/blog.css}" rel="stylesheet" /> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> </head> <body> <h3>th:each</h3> <table class="writer_css_class"> <tr th:each="writer : ${writers}"> <td th:text="${writer.name}">Name</td> <td th:text="${writer.location}">Location</td> <td> <a href="test.html" th:href="@{/profile/writer(id=${writer.id})}">Profile</a> </td> </tr> </table> <h3>th:each with Iteration Status</h3> <table class="writer_css_class"> <tr th:each="writer,itrStat : ${writers}" th:class="${itrStat.even}? 'even_css_class':'odd_css_class'"> <td th:text="${itrStat.count}">1</td> <td th:text="${writer.name}">name</td> <td th:text="${writer.location}">location</td> <td th:text="${itrStat.size}">0</td> </tr> </table> </body> </html>
public class ThymeleafAppUtil { public static TemplateEngine getTemplateEngine(ServletContext sc) { TemplateEngine templateEngine; ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver(sc); templateResolver.setTemplateMode("XHTML"); templateResolver.setPrefix("/WEB-INF/templates/"); templateResolver.setSuffix(".html"); templateResolver.setCacheTTLMs(3600000L); templateEngine = new TemplateEngine(); templateEngine.setTemplateResolver(templateResolver); return templateEngine; } }
public class Writer { private int id; private String name; private String location; public Writer(int id, String name, String location) { this.id = id; this.name = name; this.location = location; } // Setters and Getters public static List<Writer> getWriters() { List<Writer> list = new ArrayList<>(); list.add(new Writer(1,"Ram","Ayodhya")); list.add(new Writer(2,"Krishna","Mathura")); list.add(new Writer(3,"Shankar","Varanasi")); list.add(new Writer(4,"Hanuman","Krishkindha")); return list; } }
public class BlogApplication { public void process(HttpServletRequest request, HttpServletResponse response) throws IOException { WebContext ctx = new WebContext(request, response, request.getServletContext(), request.getLocale()); ctx.setVariable("writers", Writer.getWriters()); ThymeleafAppUtil.getTemplateEngine(request.getServletContext()).process("myblog", ctx, response.getWriter()); } }
@WebServlet(urlPatterns = "/myblog", loadOnStartup = 1) public class BlogServlet extends HttpServlet { private static final long serialVersionUID = 1L; public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException{ doGet(request,response); } public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException{ response.setContentType("text/html;charset=UTF-8"); response.setHeader("Pragma", "no-cache"); response.setHeader("Cache-Control", "no-cache"); response.setDateHeader("Expires", 0); BlogApplication application = new BlogApplication(); application.process(request, response); } }
myblog.title= Thymeleaf Blog
.even_css_class { background-color:blue; } .odd_css_class { background-color:grey; } .writer_css_class { width:200px; }
