What is Iteration?
Iteration is the repetition of a process in order to generate a sequence of outcomes.
Each repetition of the process is a single iteration,
and the outcome of each iteration is then the starting point of the next iteration.
How to achieve iteration in thymeleaf?
In thymeleaf iteration is achieved by using th:each attribute
This thymeleaf attribute will accept and iterate over some different datatypes, such as:
1- Objects implementing java.util.iterable
2- Object implementing java.util.map
3- Arrays
NOTE- Any other object is treated as if it were a single valued list containing one element.
What is Status variable?
Thymeleaf also enables a useful mechanism to keep track of the iteration process via the status variable
The status variable provide the following properties:
index : The current iteration index start with 0.
count : The number of elements processed so far.
size : The total no of elements in the list.
even/odd : Check if the current iteration index is even.
first: Check if the curent iteration is the first one.
last: check if the current iteration is the last one.
thymeleaf-springboot-tutorial --> src/main/resources --> templates --> itteration.html
<!DOCTYPE html>
<html xmlns:th="//www.thymeleaf.org">
<head>
<meta charset="ISO-8859-1">
<title>List from Iteration in Thymeleaf</title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css"
integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u"
crossorigin="anonymous">
</head>
<body>
<table class="table">
<thead>
<tr>
<th scope="col">Employee First Name </th>
<th scope="col"> Employee Last Name</th>
<th scope="col">Employee Email</th>
</tr>
</thead>
<tbody>
<tr th:each="employee:${employees}">
<td th:text="${employee.firstName}" ></td>
<td th:text="${employee.lastName}"></td>
<td th:text="${employee.email}"></td>
</tr>
</tbody>
</table>
</body>
</html>
thymeleaf-springboot-tutorial --> src/main/java -->net.javaguides.springboot -->EmployeeContoller.java
package net.javaguides.springboot;
import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class EmployeeController {
@GetMapping("/itteration")
public String boottstrap(Model model) {
List<Employees> employees= new ArrayList();
employees.add(new Employees("Harry","Potter","harry@gmail.com"));
employees.add(new Employees("Lily","Flower","lily@gmail.com"));
employees.add(new Employees("James","Riddle","jamey@gmail.com"));
employees.add(new Employees("Severus","Snape","love@gmail.com"));
employees.add(new Employees("Naruto","Uzumaki","hokage@gmail.com"));
model.addAttribute("employees", employees);
return "itteration";
}
}
Image 1
Image 2 - th:each working
Comments
Post a Comment