Explain Codes LogoExplain Codes Logo

How to do if-else in Thymeleaf?

html
thymeleaf
conditional-rendering
spring-security
Alex KataevbyAlex Kataev·Aug 4, 2024
TLDR

Perform if-else logic in Thymeleaf with th:if for the if clause and th:else or a negated th:if for else. Take a look at this:

<span th:if="${condition}" th:text="'True case'"></span> <span th:else th:text="'False case'"></span>

And for those in a hurry, the condensed ternary operator way:

<span th:text="${condition} ? 'True case' : 'False case'"></span>

That was easy, right? But wait, there's more!

Switch-case structures using th:switch and th:case

When you need to handle a multitude of conditions, th:switch and th:case are your loyal servants. These attributes evaluate a condition once and apply the match to multiple cases, preventing the need for writing additional th:if statements. Here's how:

<div th:switch="${user.role}"> <p th:case="'admin'" th:text="'User is an admin.'"></p> <!-- Here comes the boss --> <p th:case="'user'" th:text="'User is a regular user.'"></p> <!-- Just a regular Joe --> <p th:case="* th:text="'Unknown role.'"></p> <!-- Stranger in town, eh? --> </div>

Asterisk * stars as the default case if no specific case matches. What a hard worker!

Minimize redundancy using th:with

If you are evaluating the same complex expression multiple times and find it wasteful, meet th:with. You can assign the result of the expression to a local variable and reuse it. Take a look:

<div th:with="userStatus=${session.user != null}"> <div th:if="${userStatus}" th:text="'Welcome back, ' + ${session.user.name} + '!'"></div> <!-- Welcome to the jungle --> <div th:unless="${userStatus}" th:text="'Please log in.'"></div> <!-- Stranger danger --> </div>

It's like remembering someone's name at a party. Done once, used multiple times!

Secure conditionals with thymeleaf-extras-springsecurity5

Got security on your mind? No worries! Thymeleaf shines with Spring Security through thymeleaf-extras-springsecurity5. You can securely display content based on authentication and authorization states:

<div th:if="${#authorization.expr('hasRole(''ADMIN'')')}"> <!-- Admins' secret stash --> </div>

Now, you're not just checking if the user is logged in but also if they have secret spy clearances (aka roles).

Responsive text display with th:text

When your text needs to adapt according to certain conditions, th:text is your font. It harmonizes with conditional expressions to morph your text on the go:

<span th:text="${user.isAdmin()} ? 'Admin Dashboard' : 'User Profile'"></span>

It's like magic ink from Harry Potter. It changes as per your needs!

Customized user experience in real-world scenarios

Aim to present a different set of options and information to a logged-in user versus an anonymous user. Just like showing different menus in a restaurant:

<span th:if="${user.loggedIn}" th:text="'Logout'"></span> <!-- We bid you farewell --> <span th:unless="${user.loggedIn}" th:text="'Login/Register'"></span> <!-- Welcome aboard, matey! -->