Thymeleaf 教程

switch 语句

Thymeleaf 中,除了 th:if 还有一种方法是使用相当于 Java 中的 switch 结构有条件地显示内容:th:switch / th:case 属性集。

<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:switch 中某个 th:case 属性被评估为 true,则同一 th:switch 上下文中的其他 th:case 属性都将被评估为 false。

我们可以通过使用 th:case="*" 来指定一个默认选项,当所有其他 th:case 均没有匹配,则执行该 th:case。如下:

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

示例

根据性别代码,显示对应的中文性别。例如:

<div th:switch="${user.sex}">
    <div th:case="1">男</div>
    <div th:case="2">女</div>
    <!-- 默认 th:case -->
    <div th:case="*">未知</div>
</div>

当 ${user.sex} 为 1 时,则模板输出为:

<div>
    <div>男</div>
</div>
说说我的看法
全部评论(
没有评论
关于
本网站属于个人的非赢利性网站,转载的文章遵循原作者的版权声明,如果原文没有版权声明,请来信告知:hxstrive@outlook.com
公众号