Skip to content
Advertisement

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

By using Thymeleaf as template engine, is it possible to add/remove dynamically a CSS class to/from a simple div with the th:if clause?

Normally, I could use the conditional clause as follows:

<a href="lorem-ipsum.html" th:if="${condition}">Lorem Ipsum</a> 

We will be creating a link to the lorem ipsum page, but only if condition clause is true.

I’m looking for something different: I’d like the block to always visible, but with changeable classes according to the situation.

Advertisement

Answer

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>
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement