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?
Nor
For this purpose and if i dont have boolean variable i use the following:
<li th:class="${#strings.contains(content.language,'CZ')} ? active : ''">
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>
What @Nilsi mentioned is perfectly correct. However, adminclass and user class need to be wrapped in single quotes as this might fail due to Thymeleaf looking for adminClass or userclass variables which should be strings. That said,
it should be: -
<a href="" class="baseclass" th:classappend="${isAdmin} ? 'adminclass' :
'userclass'">
</a>
or just:
<a href="" th:class="${isAdmin} ? 'newclass' :
'baseclass'">
</a>
If you just want to append a class in case of an error you can use th:errorclass="my-error-class"
mentionned in the doc.
<input type="text" th:field="*{datePlanted}" class="small" th:errorclass="fieldError" />
Applied to a form field tag (input, select, textarea…), it will read the name of the field to be examined from any existing name or th:field attributes in the same tag, and then append the specified CSS class to the tag if such field has any associated errors