vdenotaris vdenotaris - 5 months ago 250
CSS Question

Thymeleaf: how to use conditionals to add/remove dynamically 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 a block always visible, but with changeable classes according to the situation.

Answer

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>