Thymeleaf Standard Expressions

In this tutorial, you will learn five types of Thymeleaf Standard Expressions - Variable, Selection, Message, Link, and Fragment expressions.

Check out the complete Thymeleaf tutorials and examples at Thymeleaf Tutorial

Thymeleaf Standard Expressions

There are five types of Thymeleaf standard expressions:​ 
  1. ${...}: Variable expressions​ 
  2. *{...} : Selection expressions​ 
  3. #{...} : Message (i18n) expressions​ 
  4. @{...} : Link (URL) expressions​ 
  5. ~{...}: Fragment expressions
Let's understand each of these Thymeleaf Standard Expressions with an example.

1. Variable Expressions

Variable expressions are the most commonly used ones in the Thymeleaf templates. These expressions help bind the data from the template context(model) into the resulting HTML(view). 

Syntax: 
${VariableName}

1.1 Variable Expressions Example

Consider we have added data to the model in Spring MVC controller and in order to access the model data, we use the Thymeleaf Variable expressions.

Let's create a Spring boot project using the spring initializr and add Spring Web and Thymeleaf dependencies:
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-thymeleaf</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
Next, let's create a User model class with the following content into it:
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;
    }
}
Next, let's create a Spring MVC controller (UserController) with a handler method to return the Thymeleaf template like:
package net.javaguides.thymeleaf.controller;

import net.javaguides.thymeleaf.model.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class UserController {

    // handler method to handle variable-expression request
    @GetMapping("variable-expression")
    public String variableExpression(Model model){
        User user = new User("Ramesh", "[email protected]", "ADMIN", "Male");
        model.addAttribute("user", user);
        return "variable-expression";
    }
}
Spring boot will auto-configure ViewResolver for Thymeleaf whenever it will find the springboot-thymeleaf-starter dependency on the classpath hence we don't have to manually configure ViewResolver for Thymeleaf.

Here is the Thymeleaf template that demonstrates the usage of variable expressions:
<!DOCTYPE html>
<html lang="en"
    xmlns:th="http://www.thymeleaf.org"
>
<head>
    <meta charset="UTF-8">
    <title>Variable Expressions</title>
</head>
<body>
<h1>Variable Expression Demo:</h1>
<h2>User Details:</h2>
<div>
    <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>
</div>
</body>
</html>

Demo:

Run the Spring boot application and hit the below link in the browser:

Here is the output:

2. Selection Expressions​

Selection expressions are just like variable expressions, except they will be executed on a previously selected object instead of the whole context variables map. 

To use selection expressions you first need to define a th:object attribute. After that, You can use the selection expressions to select the attributes/fields of the selected object.

2.1  Selection Expressions​ Example

Let's understand Selection expressions with an example.

1. Let's add the below handler method in a UserController to return the Thymeleaf template like:
    // handler method to handle selection expression
    // http://localhost:8080/selection-expression
    @GetMapping("selection-expression")
    public String selectionExpression(Model model){
        User user = new User("Ramesh", "[email protected]", "ADMIN", "Male");
        model.addAttribute("user", user);
        return "selection-expression";
    }
2. Here is the Thymeleaf template that demonstrates the usage of Selection expressions:
<!DOCTYPE html>
<html lang="en"
    xmlns:th="http://www.thymeleaf.org"
>
<head>
    <meta charset="UTF-8">
    <title>Selection Expressions</title>
</head>
<body>
<h1>Selection Expressions Demo</h1>
<h2>User Details:</h2>
<div th:object="${user}">
    <p> Name: <strong th:text="*{name}"></strong></p>
    <p> Email: <strong th:text="*{email}"></strong></p>
    <p> Role: <strong th:text="*{role}"></strong></p>
    <p> Gender: <strong th:text="*{gender}"></strong></p>
</div>
</body>
</html>
3. Run the Spring boot application and hit the below link in the browser:

Here is the output:

3. Message Expressions​

Message expressions let you externalize common texts into a properties file. 

Syntax: 
#{message.property.key}
Let’s say you have a welcome message that you want to show on every view. However, hardcoding this message on all of these views is a bad idea.

3.1 Message Expressions​ Example

Let's understand Message expressions with an example.

1. Create a messages.properties file under /resources folder and add the following content:
app.name=Spring Boot Thymeleaf Application
welcome.message=Hello, welcome to Spring boot application
2. Let's add the below handler method in a UserController to return the Thymeleaf template like:
    // handler method to handle message expressions request
    // http://localhost:8080/message-expression
    @GetMapping("message-expression")
    public String messageExpression(){
        return "message-expression";
    }
3. Here is the Thymeleaf template that demonstrates the usage of Message expressions:
<!DOCTYPE html>
<html lang="en"
    xmlns:th="http://www.thymelaf.org"
>
<head>
    <meta charset="UTF-8">
    <title>Message Expressions</title>
</head>
<body>
<h1>Message Expressions Demo:</h1>
<h2 th:text="#{app.name}"></h2>
<h2 th:text="#{welcome.message}"></h2>
</body>
</html>
4. Run the Spring boot application and hit the below link in the browser:

Here is the output:


4. Link Expressions

Link expressions are meant to build URLs in Thymeleaf templates. 

Syntax:
@{link}

4.1 Link Expressions Example

Let's understand Link expressions with an example.

1. Let's add the below handler method in a UserController to return the Thymeleaf template like:

    // handler method to handle link expressions
    // http://localhost:8080/link-expression
    @GetMapping("link-expression")
    public String linkExpression(Model model){
        model.addAttribute("id", 1);
        return "link-expression";
    }
2. Here is the Thymeleaf template that demonstrates the usage of Link expressions:
<!DOCTYPE html>
<html lang="en"
    xmlns:th="http://www.thymeleaf.org"
>
<head>
    <meta charset="UTF-8">
    <title>Link Expressions</title>
    <link th:href="@{/css/demo.css}" rel="stylesheet" />
</head>
<body>
<h1>Link Expressions Demo:</h1>
<a th:href="@{/variable-expression}"> variable-expression </a>
<a th:href="@{/selection-expression}"> selection-expression </a>
<p> <a th:href="@{link-expression/{id}(id=${id})}">link with parameter</a></p>
</body>
</html>
3. Run the Spring boot application and hit the below link in the browser:

Here is the output:

5. Fragment Expressions

Fragment expressions are an easy way to represent fragments of markup and move them around templates. 

Syntax: 
~{fragment name} 
There are three basic ways to include content from a fragment: 
  1. th:insert – inserts content inside the tag 
  2. th:replace – replaces the current tag with the tag defining the fragment 
  3. th:include – this is deprecated but it may still appear in a legacy code

5.1 Fragment Expressions Example

Let's understand Fragment expressions with an example.

1. Let's first create a new folder called the common in /resources/templates folder. Within the common folder, let's create header.html and footer.html Thymeleaf HTML files.

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>
2. Let's add the below handler method in a UserController to return the Thymeleaf template like:
    // handler method to handle fragment expression
    @GetMapping("fragment-expression")
    public String fragmentExpression(){
        return "fragment-expression";
    }
3. Here is the Thymeleaf template that demonstrates the usage of Fragment expressions:
<!DOCTYPE html>
<html lang="en"
  xmlns:th="http://www.thymeleaf.org"
>
<head>
    <meta charset="UTF-8">
    <title>Fragment Expression</title>
</head>
<body>
<h1> Fragment Expressions Demo:</h1>
<div th:replace="~{common/header :: header}"></div>
<div>
    <h1>Page Body</h1>
</div>
<div th:replace="~{common/footer :: footer}"></div>
</body>
</html>
4. Run the Spring boot application and hit the below link in the browser:

Here is the output:

Conclusion

In this tutorial, you learned five types of Thymeleaf Standard Expressions with examples - Variable, Selection, Message, Link, and Fragment expressions.

Comments