【问题标题】:If-Else in a th:each statement in ThymeleafThymeleaf 中的 th:each 语句中的 If-Else
【发布时间】:2014-07-07 10:02:51
【问题描述】:

我想要的是 Thymeleaf 中 th:each 语句中的 if-else。

If currentSkill != null,然后显示带有内容的表格,否则'你没有任何技能'

这是没有 if/else 的代码:

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

【问题讨论】:

    标签: spring-mvc thymeleaf


    【解决方案1】:
    <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

    请注意,在这两种情况下,isEmpty() 都会返回 true,无论对象为 null 还是包含零项。

    【讨论】:

    • Tnx 这么多!第二种解决方案正是我需要的。
    • th:unless 是防止 ! 的另一种选择
    • 那么您如何在th:each 中按项目进行操作?
    • @mmcrae 你能澄清一下吗?
    • @RachitAgrawal 您可以使用th:with轻松地将表达式的结果存储在局部变量中
    【解决方案2】:

    你可以使用

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-10-28
      • 1970-01-01
      • 1970-01-01
      • 2023-03-28
      • 1970-01-01
      • 2019-04-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多