Thymeleaf: 如何使用条件语句动态添加/删除 CSS 类

通过使用 百里香叶作为模板引擎,是否可以动态地向带有 th:if子句的简单 div添加/删除 CSS 类?

通常情况下,我可以使用条件从句如下:

<a href="lorem-ipsum.html" th:if="${condition}">Lorem Ipsum</a>

我们将创建一个到 Lorem ipsum页面的链接,但只有当条件子句为 true 时才会这样做。

我正在寻找一些不同的东西: 我希望块总是可见的,但可以根据情况更改类。

140190 次浏览

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>

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>

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

<li th:class="${#strings.contains(content.language,'CZ')} ? active : ''">

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

<li th:class="${#strings.equals(pageTitle,'How It Works')} ? active : ''">

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>

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.

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

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.

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>

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>