Thymeleaf: how to use conditionals to dynamically add/remove a CSS class

后端 未结 10 972
無奈伤痛
無奈伤痛 2020-12-12 15:04

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

相关标签:
10条回答
  • 2020-12-12 15:05

    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.

    0 讨论(0)
  • 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>
    
    0 讨论(0)
  • 2020-12-12 15:13

    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> 
    
    0 讨论(0)
  • 2020-12-12 15:14

    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.

    0 讨论(0)
  • 2020-12-12 15:21

    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>
    
    0 讨论(0)
  • 2020-12-12 15:23

    Another very similar answer is to use "equals" instead of "contains".

    <li th:class="${#strings.equals(pageTitle,'How It Works')} ? active : ''">
    
    0 讨论(0)
提交回复
热议问题