Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 322
vdenotaris Avatar asked Aug 05 '14 07:08

vdenotaris


People also ask

What is Classappend?

Use th:style or th:styleappend or both helps you establish values for the style attributes based on a condition. th:style. th:style will create a the style attribute (or replace the available style attribute) during generating HTML by the Thymeleaf Engine. (Template) <p style ="color: blue;" th:style = "${isAdmin} ? '

How do you set a variable in Thymeleaf?

We can use the th:with attribute to declare local variables in Thymeleaf templates. A local variable in Thymeleaf is only available for evaluation on all children inside the bounds of the HTML tag that declares it.


2 Answers

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> 
like image 68
nilsi Avatar answered Oct 08 '22 21:10

nilsi


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>  
like image 24
Michiel Bijlsma Avatar answered Oct 08 '22 21:10

Michiel Bijlsma