Explain Codes LogoExplain Codes Logo

Thymeleaf: how to use conditionals to dynamically add/remove a CSS class

html
conditional-statements
thymeleaf
dynamic-class-manipulation
Nikita BarsukovbyNikita Barsukov·Sep 30, 2024
TLDR

Dynamically toggle a CSS class in Thymeleaf using the th:classappend attribute. It applies a 'desired-classwhen theconditionistrue, nothing when false`.

<div th:classappend="${condition} ? 'desired-class' : ''">...</div>

But, we live in an and/or world (Schrodinger’s cat agrees 🐱), hence handle multiple classes, form errors & string comparisons too.

<!-- Walking the tightrope between multiple classes --> <div th:classappend="${isAdmin} ? 'admin-class other-class' : 'user-class'"></div> <!-- Clumsy keyboard? No problem --> <div th:classappend="${error} ? 'invalid-input' : 'no-error'"></div> <!-- Are you an Admin or an ADMIN? Let's find out --> <div th:class="${#strings.equals(userRole, 'ADMIN')} ? 'admin-class' : ''"></div>

Conditional class manipulation: The breakdown

Thumb rule: Clean HTML

Hygiene matters, even in HTML. Introduce dynamic class variations using th:class and th:classappend. They let you switch or append classes, not a hair out of place in your HTML.

<!-- Being 'decisive': Switching classes --> <div th:class="${isAdmin} ? 'admin-class' : 'user-class'"></div> <!-- No trespassing: Append without invading others’ space --> <nav th:classappend="${activeTab == 'home'} ? 'active' : ''">Home</nav>

Forms and validation: Error-proofing

Loved forms till you met form validation? th:errorclass dynamically adds a class to a field with an error. Error handling just got cooler!

<!-- Caught in the crosshairs: Dynamic error class --> <input type="text" name="username" th:errorclass="error-field" />

Logical operations: Catch 'em all

Multi-task without breaking a sweat. Add double ampersand && for AND operations and double pipe || for OR operations.

<!-- AND/OR collaboration --> <div th:classappend="${isLoggedIn && hasMessages} ? 'highlight' : 'normal'"></div>

Beefing up: Advanced use and solutions

Lists and complex structures

Ever toggled classes inside a loop? Time to tour the ${#iteration} universe. Warning: Beware of the paradox!

<!-- Going around in circles: Toggle within --> <ul> <li th:each="item, iterStat : ${items}" th:classappend="${iterStat.even} ? 'even' : 'odd'"> [[${item.name}]] </li> </ul>

String comparisons: The litmus test

#strings.equals and #strings.contains to the rescue for string matching. Beard stroking ends here!

<!-- Litmus: String-perfect --> <div th:classappend="${#strings.contains(item.type, 'important')} ? 'highlight' : 'normal'"></div>

Best practices: Golden rules

  • Keep syntax crisp. Your grandma should understand it.
  • Variables in your controller, not inline expressions. Clarity > clutter.
  • Escape literal text. Single quotes ' are your best friends.
  • Chain expressions. Your code stays modular, you stay stress-less.