1. 概述
在本快速教程中,我們將學習幾種不同的方法來在 Thymeleaf 中條件添加 CSS 類。
如果您不熟悉 Thymeleaf,我們建議您查看關於它的介紹。
2. 使用 <em th:if="... "</em>
假設我們的目標是生成一個 `
在將此 HTML 服務之前,我們需要一種好的方法,讓服務器能夠評估一個條件,並根據條件結果添加 condition-true 類或 condition-false 類,以及 base 類。 在模板 HTML 時,通常需要添加一些條件邏輯以實現動態行為。 首先,我們使用 th:if 來演示最簡單的條件邏輯。 我們這裏可以觀察到,這將會邏輯上導致正確的 CSS 類被附加到我們的 HTML 元素上,但這個解決方案違反了 DRY 原則,因為它需要複製整個代碼塊。 使用 th:if 肯定在某些情況下很有用,但我們應該尋找另一種動態添加 CSS 類的方法。 Thymeleaf 提供了 讓我們使用它來解決我們的問題: 您可能注意到 base 類仍然被重複使用。此外,我們還可以使用更具體的 Thymeleaf 屬性來定義類。 這個解決方案相當不錯,因為它滿足了我們的需求並且遵循了 DRY 原則。但是,我們還可以從另一個 Thymeleaf 屬性中獲益。 Wouldn’t it be nice to completely decouple our base class from the conditional logic? 我們可以靜態定義我們的 隨着我們 Thymeleaf 代碼的每一次迭代,我們學習了一種有用的條件判斷技術,這在未來可能會派上用場。最終,我們發現使用 `<em th:classappend<span class="base condition-true">
I have two classes: "base" and either "condition-true" or "condition-false" depending on a server-side condition.
</span><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>3. 使用
th:attr 屬性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>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>5. 使用
<em th:classappend</em><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. 結論