在Thymeleaf的th:each语句中使用If-Else

6

我希望在Thymeleaf的th:each语句中使用if-else。

如果currentSkill!= null,则显示包含内容的表格,否则显示“您没有任何技能”。

这是没有if / else的代码:

<div th:each="skill : ${currentSkills}">
    <table>
         <tr><td th:text="${skill.name}"/></tr>
    </table>
</div>
2个回答

17
<div  th:if="${currentSkills != null}">
    <table>
         <tr th:each="skill : ${currentSkills}"><td th:text="${skill.name}"/></tr>
    </table>
</div>
<div th:if="${currentSkills == null}">
   You don't have any skills
</div>

如果currentSkills是一个列表,你可以使用#lists工具,像这样(比上面的代码更正确,因为它还考虑了对象不为空但为空的可能性):

 <div  th:if="!${#lists.isEmpty(currentSkills)}">
    <table>
         <tr th:each="skill : ${currentSkills}"><td th:text="${skill.name}"/></tr>
    </table>
</div>
<div th:if="${#lists.isEmpty(currentSkills)}">
   You don't have any skills
</div>

如果currentSkills是一个数组,您可以通过将#lists替换为#arrays来执行相同的操作。

请注意,在这两种情况下,如果对象为null或项目数为零,isEmpty()都会返回true。


th:unless是另一种选项,可以防止! - niels
那么在 th:each 中如何按每个项目进行操作呢? - Don Cheadle
@mmcrae,您能否稍微澄清一下? - geoand
我的目标是遍历一个对象列表,如果该列表中的对象属性等于“a”,则显示“X”,否则显示“Y”,并对列表中的每个对象执行此操作。 - Don Cheadle
1
@RachitAgrawal 你可以使用 th:with 轻松地将表达式的结果存储在本地变量中。 - geoand
显示剩余3条评论

1

您可以使用

<div  th:if="${!currentSkills.isEmpty()}">
    <table>
         <tr th:each="skill : ${currentSkills}"><td th:text="${skill.name}"/></tr>
    </table>
</div>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接