Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
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 th:if="${currentSkills != null}">
<table>
<tr th:each="skill : ${currentSkills}"><td th:text="${skill.name}"/></tr>
</table>
<div th:if="${currentSkills == null}">
You don't have any skills
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 th:if="${#lists.isEmpty(currentSkills)}">
You don't have any skills
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.
–
<div th:if="${!currentSkills.isEmpty()}">
<table>
<tr th:each="skill : ${currentSkills}"><td th:text="${skill.name}"/></tr>
</table>
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.