Labs ICT
⭐ Pro Login

Expression Types

Variable, selection, message, and URL expressions.

2 min read | Thymeleaf Tutorial
⭐

Want the full learning experience?

Get structured courses, certificates, projects, and instructor support with LabsICT Pro.

Explore Pro Courses

Expression Types

Thymeleaf has several types of expressions. Each one does something different. Let's break them down so you know exactly when to use each one.

Variable Expressions ${}

The variable expression ${...} is the one you'll use most. It accesses data from the model, request parameters, or beans.


<p th:text="${username}">Guest</p>
<p th:text="${user.name}">User Name</p>
<p th:text="${list.size()}">0</p>
    

You can call methods, access properties, and do pretty much anything you'd do in Java. It uses Spring EL (SpEL) under the hood.

Selection Expressions *{}

Selection expressions work like variable expressions but on a previously selected object. Use th:object to select, then *{...} to access properties.


<div th:object="${user}">
    <p th:text="*{name}">Name</p>
    <p th:text="*{email}">Email</p>
</div>
    

This is cleaner when you're accessing multiple properties of the same object. No need to repeat ${user.name}, ${user.email} every time.

Message Expressions #{}

Message expressions access internationalized messages from properties files. They're great for multi-language apps.


<p th:text="#{welcome.message}">Welcome!</p>
<p th:text="#{greeting(${username})}">Hello!</p>
    

Thymeleaf looks up the key in your messages.properties file. You can pass parameters with parentheses for dynamic messages.

URL Expressions @{}

URL expressions build links and URLs. They handle context paths and session IDs automatically.


<a th:href="@{/home}">Home</a>
<a th:href="@{/user/{id}(id=${userId})}">Profile</a>
<form th:action="@{/search}" method="get">...</form>
    

The @{...} syntax ensures your URLs work correctly regardless of the application's context path. Always use it for links and form actions.