知識庫 / Spring / Spring MVC RSS 訂閱

Thymeleaf 條件 CSS 類

Spring MVC
HongKong
4
12:53 PM · Dec 06 ,2025

1. 概述

在本快速教程中,我們將學習幾種不同的方法來在 Thymeleaf 中條件添加 CSS 類。

如果您不熟悉 Thymeleaf,我們建議您查看關於它的介紹。

2. 使用 <em th:if="... "</em>

假設我們的目標是生成一個 `

<span class="base condition-true">
   I have two classes: "base" and either "condition-true" or "condition-false" depending on a server-side condition.
</span>

在將此 HTML 服務之前,我們需要一種好的方法,讓服務器能夠評估一個條件,並根據條件結果添加 condition-true 類或 condition-false 類,以及 base 類。

在模板 HTML 時,通常需要添加一些條件邏輯以實現動態行為。

首先,我們使用 th:if 來演示最簡單的條件邏輯。

<span th:if="${condition}" class="base condition-true">
   This HTML is duplicated. We probably want a better solution.
</span>
<span th:if="${!condition}" class="base condition-false">
   This HTML is duplicated. We probably want a better solution.
</span>

我們這裏可以觀察到,這將會邏輯上導致正確的 CSS 類被附加到我們的 HTML 元素上,但這個解決方案違反了 DRY 原則,因為它需要複製整個代碼塊。

使用 th:if 肯定在某些情況下很有用,但我們應該尋找另一種動態添加 CSS 類的方法。

3. 使用 th:attr 屬性

Thymeleaf 提供了 th:attr 屬性,允許我們定義其他屬性。

讓我們使用它來解決我們的問題:

<span th:attr="class=${condition ? 'base condition-true' : 'base condition-false'}">
   This HTML is consolidated, which is good, but the Thymeleaf attribute still has some redundancy in it.
</span>

您可能注意到 base 類仍然被重複使用。此外,我們還可以使用更具體的 Thymeleaf 屬性來定義類。

4. 使用 <em th:class</em> 屬性

<em th:class</em> 屬性是 <em th:attr=”class=…”</em> 的簡寫,因此我們應該使用它,同時將 <em base</em> 類從條件結果中分離出來:

<span th:class="'base '+${condition ? 'condition-true' : 'condition-false'}">
   The base CSS class still has to be appended with String concatenation. We can do a little bit better.
</span>

這個解決方案相當不錯,因為它滿足了我們的需求並且遵循了 DRY 原則。但是,我們還可以從另一個 Thymeleaf 屬性中獲益。

5. 使用 <em th:classappend</em>

Wouldn’t it be nice to completely decouple our base class from the conditional logic? 我們可以靜態定義我們的 <em th:classappend</em> 類,並將條件邏輯限制為僅包含相關的部分:

<span class="base" th:classappend="${condition ? 'condition-true' : 'condition-false'}">
   This HTML is consolidated, and the conditional class is appended separately from the static base class.
</span>

6. 結論

隨着我們 Thymeleaf 代碼的每一次迭代,我們學習了一種有用的條件判斷技術,這在未來可能會派上用場。最終,我們發現使用 `<em th:classappend 能夠為我們提供 DRY 代碼和分層設計之間的最佳平衡,同時滿足我們的目標。

user avatar
0 位用戶收藏了這個故事!
收藏

發佈 評論

Some HTML is okay.