Working with Variables
Understanding where your data comes from is key to using Thymeleaf effectively. Let's look at all the ways you can pass variables to your templates.
Model Attributes
The most common way is using Model.addAttribute() in your controller. The data is available in the template through the ${...} expression.
@GetMapping("/dashboard")
public String dashboard(Model model) {
model.addAttribute("username", "Alice");
model.addAttribute("age", 28);
return "dashboard";
}
Then in your template, just use ${username} and ${age}. Spring makes them available automatically.
Request Parameters
You can also access request parameters directly in the template. No controller code needed.
<p th:text="${param.search}">Search term</p>
<p th:text="${param.page}">Page number</p>
If the URL is /results?search=thymeleaf&page=2, these expressions will display those values. Simple and convenient.
Session Attributes
Data stored in the session is available through the session object. This is useful for data that needs to persist across multiple requests.
<p th:text="${session.cart.totalItems}">0</p>
<p th:text="${session.user.role}">Role</p>
Just make sure you've set these attributes in your controller or somewhere else in your code first.
Null Handling
What happens when a variable is null? Thymeleaf replaces the element's content with nothing. The default text you put inside the tag won't show either.
<p th:text="${missingVar}">This default text disappears if null</p>
To show a fallback, use the ternary operator:
<p th:text="${username ?: 'Guest'}">Guest</p>
If username is null, it shows "Guest" instead of nothing. Always plan for nulls in your templates.