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

vdenotaris picture vdenotaris · Aug 5, 2014 · Viewed 110.7k times · Source

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.

Answer

nilsi picture nilsi · Nov 17, 2014

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>