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

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


There is also th:classappend.

<a href="" class="baseclass" th:classappend="${isAdmin} ? adminclass : userclass"></a>

If isAdmin is true, then this will result in:

<a href="" class="baseclass adminclass"></a>


Yes, it is possible to change a CSS class dynamically according to the situation, but not with th:if. This is done with the elvis operator.

<a href="lorem-ipsum.html" th:class="${isAdmin}? adminclass : userclass">Lorem Ipsum</a> 


For this purpose and if i dont have boolean variable i use the following:

<li th:class="${#strings.contains(content.language,'CZ')} ? active : ''">