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
Yet another usage of th:class, same as @NewbLeech and @Charles have posted, but simplified to maximum if there is no "else" case:
<input th:class="${#fields.hasErrors('password')} ? formFieldHasError" />
Does not include class attribute if #fields.hasErrors('password') is false.
Just to add my own opinion, in case it might be useful to someone. This is what I used.
<div th:class="${request.read ? 'mdl-color-text--grey-800 w500' : ''}"> </div>
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 are looking to add or remove class accordingly if the url contains certain params or not .This is what you can do
<a th:href="@{/admin/home}" th:class="${#httpServletRequest.requestURI.contains('home')} ? 'nav-link active' : 'nav-link'" >
If the url contains 'home' then active class will be added and vice versa.
Just in case someone is using Bootstrap, I was able to add more than one class:
<a href="" class="baseclass" th:classappend="${isAdmin} ?: 'text-danger font-italic' "></a>
Another very similar answer is to use "equals" instead of "contains".
<li th:class="${#strings.equals(pageTitle,'How It Works')} ? active : ''">