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.
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} ? '
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With