If-Else in a th:each statement in Thymeleaf

…衆ロ難τιáo~ 提交于 2021-02-05 20:37:01

问题


What I want is an if-else in a th:each statement in Thymeleaf.

If currentSkill != null, then show table with content, else 'You don't have any skills'

This is the code without the if/else:

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

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

If currentSkills is a list, you can use the #lists utility like so (which is more correct than the above code since it also takes into account the possibility where the object is not null but is empty):

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

You could do the same if currentSkills is an array by just replacing #lists with #arrays.

Note that in both cases isEmpty() returns true whether the object is null or has zero items.




回答2:


You can use

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


来源:https://stackoverflow.com/questions/23737836/if-else-in-a-theach-statement-in-thymeleaf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!