Conditional Rendering
Thymeleaf lets you show or hide elements based on conditions. This is super useful for building dynamic pages where content changes based on data.
Welcome back, user!
Admin dashboard available
The th:if attribute only renders the element if the condition is true. Pretty straightforward, right?
Using th:unless
Sometimes you want to show something when a condition is false. That's where th:unless comes in. It's the opposite of th:if.
Please log in to continue
Everything looks good!
Think of it as "show this element unless this condition is true."
Boolean Conditions
You can use any expression that evaluates to a boolean. This includes checking for null, empty collections, or specific values.
User profile loaded
We have users!
There are items
Thymeleaf automatically treats null as false, empty strings as false, and empty collections as false.
Switch and Case
When you have multiple conditions to check, switch/case is your friend. It's cleaner than writing a bunch of th:if statements.
Admin panel
User dashboard
Guest view
Default view
The * case acts as a default, just like in Java switch statements.
Null Checks
Checking for null values is a common task. Thymeleaf makes it easy with its expression language.
Name here
No name provided
You can also combine null checks with other conditions for more complex logic.
Empty Collection Checks
Working with collections? Check if they're empty before trying to display their contents.
- Product
No products available
The empty keyword is a convenient way to check for null, empty strings, and empty collections.