Thymeleaf If Else Condition

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) { = name; = email;
        this.role = role;
        this.gender = gender;

    public String getName() {
        return name;

    public void setName(String name) { = name;

    public String getEmail() {
        return email;

    public void setEmail(String 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;

public class UserController {

    // if-unless condition
    public String ifUnless(Model model){
        User ramesh = new User("ramesh","", "ADMIN", "M");
        User admin = new User("admin","", "ADMIN", "M");
        User meena = new User("meena","", "USER", "F");
        List<User> users = new ArrayList<>();
        model.addAttribute("users", users);
        return "if-unless";

Create Thymeleaf template - if-unless.html

<!DOCTYPE html>
<html lang="en"
    <meta charset="UTF-8">
    <title>User Management</title>
<table border="1">
    <tr th:each="user : ${users}">
        <td th:text="${}"></td>
        <td th:text="${}"></td>
        <td th:text="${user.role}"></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>
If the User role is 'ADMIN' then the Update and Delete buttons will be rendered unless the View button will be rendered.


Run your Spring boot application and hit this URL in a browser: