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

后端 未结 10 973
無奈伤痛
無奈伤痛 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:26

    For this purpose and if i dont have boolean variable i use the following:

    <li th:class="${#strings.contains(content.language,'CZ')} ? active : ''">
    
    0 讨论(0)
  • 2020-12-12 15:28

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

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

    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

    0 讨论(0)
提交回复
热议问题