1. 概述

本文将介绍在 Thymeleaf 模板引擎中,如何根据条件动态添加 CSS 类的几种常用方法。

如果你对 Thymeleaf 不太熟悉,建议先阅读我们的 Thymeleaf 入门指南

2. 使用 th:if ❌

假设我们需要生成一个 <span> 标签,其 CSS 类由服务端逻辑决定:

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

我们希望在服务端根据某个条件(如 condition 变量)决定是添加 condition-true 还是 condition-false 类,同时保留固定的 base 类。

最直观的方式是使用 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>

✅ 优点:逻辑清晰,适合完全不同的结构分支。
❌ 缺点:严重违反 DRY 原则,HTML 结构完全重复,维护成本高。

⚠️ 踩坑提示:这种写法虽然能跑通,但一旦标签内容复杂,复制粘贴极易出错,不推荐用于仅类名变化的场景。

3. 使用 th:attr ✅(可行但不够优雅)

Thymeleaf 提供了 th:attr 属性,用于动态设置任意 HTML 属性。

我们可以用它来动态设置 class

<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>

✅ 优点:消除了 HTML 重复,满足 DRY。
⚠️ 问题:base 类仍然在三元表达式中重复出现,不够简洁。

📝 提示:th:attr 是通用属性设置方式,但针对 class 有更专业的替代方案。

4. 使用 th:class ✅(推荐替代 th:attr)

th:classth:attr="class=..." 的语法糖,更简洁直观:

<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>

✅ 优点:

  • 语义清晰,专用于设置 class
  • 避免了 HTML 重复
  • base 类写死,条件类动态拼接

⚠️ 仍可改进:使用字符串拼接,语法略显冗余,且容易出错(比如忘了加空格)。

5. 使用 th:classappend ✅✅(最佳实践)

Thymeleaf 还提供了 th:classappend,专门用于追加 CSS 类,完美解耦静态类和动态类:

<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>

✅ 优点:

  • 完全分离关注点:静态类写在 class 中,动态类用 th:classappend 追加
  • 无需字符串拼接,语法简洁
  • 易读易维护,不容易出错
  • 符合直觉,代码意图一目了然

💡 小技巧:当 conditionfalse 时,th:classappend 不会添加任何类,也不会报错,非常安全。

6. 总结

方法 是否推荐 适用场景
th:if 完全不同的 DOM 结构分支
th:attr ⚠️ 通用属性设置(非 class)
th:class 动态设置整个 class 属性
th:classappend ✅✅ 追加条件类,保留静态类

最终结论
在需要保留原有 CSS 类并动态追加的场景下,th:classappend 是最优雅、最安全的选择。它让模板更清晰,也更符合前端开发的直觉。

所有示例代码均可在 GitHub 上的完整 Thymeleaf 项目中找到:
https://github.com/eugenp/tutorials/tree/master/spring-web-modules/spring-thymeleaf-3


原始标题:Conditional CSS Classes in Thymeleaf