What is Thymeleaf?
-
Thymeleaf is a modern server-side Java Template engine for both web and standalone environments, capable of processing HTML, XML, JavaScript, CSS and even plain text
-
Assists in your front-end HTML designs
Natural Templates
-
HTML Templates written in Thymeleaf still look and work like HTML Templates
-
HTML can be correctly displayed in browser
-
Can also work as a static prototype (useful in team dev)
Iterating in Thymeleaf
-
th:each
- for each item in a collection of items
- similar to a for each loop traversing a List
- will iterate over a list of products, array, map or other collection
Examples
<tbody>
<tr th:each="student: ${students}">
<td th:text="${student.id}" />
<td th:text="${student.name}" />
</tr>
</tbody
Examples continued
Concatenation:
th:text="'The name of the student is ' + ${student.name}"
If/Unless
<td>
<span th:if="${student.age} > 16" th:text="You can drive" />
<span th:unless="${student.age} < 16" th:text="You cannot drive" />
</td>
Referencing
- You should match your attributes from your Controller class
In the Controller
class...ie StudentController
, imagine the following method:
@RequestMapping("/students")
public String getStudents(Model model) {
model.addAttribute("students", repository.findAll());
return "students";
}
In students.html notice the collection is referred to as students
<tr th:each="student: ${students}"></tr>