In this tutorial, we show how to use the if-else condition in Thymeleaf HTML templates.
Thymeleaf provides the th:if and th:unless attributes perform if-else condition.
The th:if and th:unless attributes allow us to render an HTML element depending on a provided condition.
Thymeleaf If Else Condition Example
Create User Model
package net.javaguides.thymeleaf.model;
public class User {
private String name;
private String email;
private String role;
private String gender;
public User(String name, String email, String role, String gender) {
this.name = name;
this.email = email;
this.role = role;
this.gender = gender;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
}
Create Spring MVC Controller - UserController
Within DemoController class, let's create a handler method to return the view and model:
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import java.util.ArrayList;
import java.util.List;
@Controller
public class UserController {
// if-unless condition
@GetMapping("if-unless")
public String ifUnless(Model model){
User ramesh = new User("ramesh","ramesh@gmail.com", "ADMIN", "M");
User admin = new User("admin","admin@gmail.com", "ADMIN", "M");
User meena = new User("meena","meena@gmail.com", "USER", "F");
List<User> users = new ArrayList<>();
users.add(ramesh);
users.add(admin);
users.add(meena);
model.addAttribute("users", users);
return "if-unless";
}
}
Create Thymeleaf template - if-unless.html
<!DOCTYPE html>
<html lang="en"
xmlns:th="http://www.thymeleaf.org"
>
<head>
<meta charset="UTF-8">
<title>User Management</title>
</head>
<body>
<table border="1">
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Role</th>
<th>Gender</th>
</tr>
</thead>
<tbody>
<tr th:each="user : ${users}">
<td th:text="${user.name}"></td>
<td th:text="${user.email}"></td>
<td th:text="${user.role}"></td>
<td>
<a class="btn btn-primary" th:if="${user.role} == 'ADMIN'">Update</a>
<a class="btn btn-danger" th:if="${user.role} == 'ADMIN'">Delete</a>
<a class="btn btn-primary" th:unless="${user.role} == 'ADMIN'">View</a>
</td>
</tr>
</tbody>
</table>
</body>
</html>
If the User role is 'ADMIN' then the Update and Delete buttons will be rendered unless the View button will be rendered.
Demo:
Run your Spring boot application and hit this URL in a browser:
Comments
Post a Comment