Thymeleaf Attributes

In this tutorial, we will learn a few important Thymeleaf attributes with examples.

We will cover:

1. Thymeleaf th:text attribute

2. Thymeleaf th:each attribute

3. Thymeleaf th:if and th:unless attribute

4. Thymeleaf th:switch and th:case attribute

5. Thymeleaf th:fragment attribute

1. Thymeleaf th:text attribute

The th:text attribute is responsible for displaying text that is evaluated from the expression inside it.​ 

For example: To display a message:

<h2 th:text="${message}">Hello Good Morning!.</h2>

The th:text attribute evaluates its value expression and sets the result as the body of the host tag, effectively replacing the “Hello Good Morning!” text we see in the code.

Thymeleaf th:text attribute example

The below example demonstrates the usage of th:text attribute to evaluate variable expressions and result as the body of the <strong> tag:

    <p> Name: <strong th:text="${user.name}"></strong></p>
    <p> Email: <strong th:text="${user.email}"></strong></p>
    <p> Role: <strong th:text="${user.role}"></strong></p>
    <p> Gender: <strong th:text="${user.gender}"></strong></p>

Read more about th:text attribute at Thymeleaf th:text Attribute

2. Thymeleaf th:each attribute

In Thymeleaf, iteration or looping is achieved by using the th:each attribute. One of the interesting things about this attribute is that it will accept and iterate over some different data types, such as List, Set, Map, Array

Thymeleaf th:each attribute example

Consider we have Employee Model class:
package net.javaguides.springboot;

public class Employee {
    private String firstName;
    private String lastName;
    private String email;

    public Employee(String firstName, String lastName, String email) {
        super();
        this.firstName = firstName;
        this.lastName = lastName;
        this.email = email;
    }
    // getters/setters   
}

Spring MVC controller that returns Model and View:

@Controller
public class EmployeeController {

    @GetMapping("/iteration")
    public String iteration(Model model) {
        List < Employee > employees = new ArrayList < > ();
        employees.add(new Employee("Ramesh", "Fadatare", "ramesh@gmail.com"));
        employees.add(new Employee("John", "Cena", "john@gmail.com"));
        employees.add(new Employee("Tom", "Cruise", "tom@gmail.com"));
        employees.add(new Employee("Tony", "Stark", "tony@gmail.com"));
        model.addAttribute("employees", employees);
        return "iteration";
    }
}
Here is the Thymeleaf template that demonstrates the usage of th:each attribute. We are using th:each to iterate through the list of employees:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">

<head>
    <meta charset="ISO-8859-1">
    <title>Add Bootstrap CSS Demo</title>

    <link th:href="@{/css/bootstrap.min.css}" rel="stylesheet" />
</head>

<body>
    <div class="container">
        <div class="row">
            <h1>Employees</h1>

            <table class="table">
                <thead>
                    <tr>
                        <th>Employee First Name</th>
                        <th>Employee Last Name</th>
                        <th>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>
        </div>

    </div>
</body>

</html>

Read more about th:each at Thymeleaf Loop or Iteration Example with Spring Boot - th:each Attribute

3. Thymeleaf th:if and th:unless attribute

In some situations, you want a certain snippet of the Thymeleaf template to appear in the result if a certain condition is evaluated as true. To do this you can use the attribute th:if.

Thymeleaf th:if and th:unless attribute example

            <table class="table">
                <thead>
                    <tr>
                        <th>User Name</th>
                        <th>User Email</th>
                    </tr>
                </thead>
                <tbody>
                    <tr th:each="user : ${users}">
                        <td th:text="${user.userName}"></td>
                        <td th:text="${user.email}"></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>

In the above Thymeleaf template, the user with the "Admin" role can only see the Update and Delete buttons. The User who doesn't have an "Admin" role can see only the View button.

Check out the complete example at Thymeleaf Template If, Unless, and Switch Case Example

4. Thymeleaf th:switch and th:case attribute

In Java, you are familiar with the switch/case structure. Thymeleaf also has a similar structure that is th:switch/th:case.
If there are more than two possible results of an expression, we can use the th:switch and th:case attributes for the conditional rendering of the HTML elements.

Thymeleaf th:switch and th:case attribute example

    <div class="container">
        <div class="row">
            <h1>Thymeleaf swith case demo</h1>
            <h4 th:utext="${user.userName}"></h4>
            <div th:switch="${user.role}">
                <p th:case="'ADMIN'">User is an administrator</p>
                <p th:case="'MANAGER'">User is a manager</p>
                <p th:case="'GUEST'">User is a guest</p>
                <!-- * for default case -->
                <p th:case="*">User is some other thing</p>
            </div>
        </div>
    </div>
If the User role is "Admin" then "User is an administrator" text prints on the web page.
The th:case = "*" is the default case of the th:swith/th:case structure. If all the above cases are evaluated as false the code of default case will be "rendered".

5. Thymeleaf th:fragment attribute

The th:fragment Thymeleaf attribute is used to define a fragment.

commom/header.html:
<!DOCTYPE html>
<html lang="en"
    xmlns:th="http://www.thymeleaf.org"
>
<head>
    <meta charset="UTF-8">
    <title>Header</title>
</head>
<body>
<div th:fragment="header">
    <h1> Header Part</h1>
    <hr />
</div>
</body>
</html>
common/footer.html:
<!DOCTYPE html>
<html lang="en"
  xmlns:th="http://www.thymeleaf.org"
>
<head>
    <meta charset="UTF-8">
    <title>Footer</title>
</head>
<body>
<div th:fragment="footer">
    <hr />
    <h1>Footer Part</h1>
</div>
</body>
</html>
Check out the complete example at Thymeleaf Fragment Expression

Related Thymeleaf Examples

  1. Thymeleaf Standard Expressions
  2. Thymeleaf th:text Attribute
  3. Thymeleaf Variable Expression
  4. Thymeleaf Selection Expression
  5. Thymeleaf Message Expression
  6. Thymeleaf Link Expression
  7. Thymeleaf Fragment Expression
  8. Introducing Thymeleaf | Thymeleaf Template | Thymeleaf Template Engine
  9. Thymeleaf Example with Spring Boot
  10. Spring Boot 3 Thymeleaf Example
  11. How to Add CSS and JS to Thymeleaf
  12. Add Bootstrap CSS to Thymeleaf
  13. How to handle null values in Thymeleaf?
  14. How to Loop a List by Index in Thymeleaf
  15. Thymeleaf Array Example - Array Index, Array Iteration
  16. Thymeleaf Enums Example
  17. Thymeleaf If Else Condition Example
  18. Thymeleaf Switch Case Example

Comments