How to do if-else in Thymeleaf?
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:
And for those in a hurry, the condensed ternary operator way:
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:
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:
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:
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:
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:
Was this article helpful?