深色模式
7.2 分支判断(Switch语句)
Thymeleaf 还提供了一种类似 Java 中 switch 结构的条件渲染方式——通过 th:switch / th:case 属性组合实现多分支判断。
html
<!-- 根据用户角色(user.role)渲染不同内容 -->
<div th:switch="${user.role}">
<p th:case="'admin'">User is an administrator</p>
<p th:case="#{roles.manager}">User is a manager</p>
</div>注意:一旦某个 th:case 的条件判定为 true,同一 th:switch 上下文下的其他 th:case 会自动判定为 false(和 Java 的 switch-case 逻辑一致,无需手动加 break);
可通过 th:case="*" 定义默认分支(等价于 Java 的 default):
html
<div th:switch="${user.role}">
<p th:case="'admin'">User is an administrator</p>
<p th:case="#{roles.manager}">User is a manager</p>
<!-- 所有分支都不匹配时渲染此内容 -->
<p th:case="*">User is some other thing</p>
</div>实用扩展示例
结合国际化和动态变量的完整场景:
html
<!-- 假设国际化配置中 roles.admin=管理员,roles.manager=经理 -->
<div th:switch="${user.role}">
<span th:case="'admin'" th:text="#{roles.admin}">管理员</span>
<span th:case="'manager'" th:text="#{roles.manager}">经理</span>
<span th:case="*" th:text="#{roles.default}">普通用户</span>
</div>注意事项
th:switch仅作用于直接子元素的th:case:如果th:case元素嵌套在其他标签内,不会被识别为分支;html<!-- 错误写法:p 标签嵌套在 div 内,不会被 switch 识别 --> <div th:switch="${user.role}"> <div> <p th:case="'admin'">管理员</p> </div> </div>- 空值处理:如果
th:switch的变量为null,会直接匹配th:case="*"分支。
总结
th:switch+th:case实现多分支条件判断,逻辑等价于 Java 的switch-case,且自带排他性(无需 break);th:case="*"作为默认分支,处理所有不匹配的情况;- 字符串常量需用单引号包裹,
th:case仅作用于th:switch元素的直接子元素。
