Reputation: 7738
I am trying to create a table in a html template only when a particular map is not empty using Thymeleaf templating engine. However, even when the map is empty, the table gets created with default values.
So, basically I have a Map<String, List<String>> myMap
which I need to check before creating the html table. I am setting the value correctly in the Context as I can verify by debugging.
<div th:if="${not #maps.isEmpty(myMap)}">
<table cellspacing='0'>
<tr th:each="instance : ${myMap.instanceMap}">
<td th:text="${instance.key}">keyvalue</td>
<td th:text="${instance.value.numOfData}">num</td>
</tr>
</table>
</div>
Also, how do I print the key versus each value for that key ( remember value is a list) in a tabular fashion ?
Upvotes: 2
Views: 7983
Reputation: 1354
Try this:
<div th:if="not ${myMap.isEmpty()}">
...
</div>
Edit: Forgot the second part of your question, you can also just iterate the list similarly. Examples:
Horizontal display:
<table cellspacing='0'>
<tr th:each="instance : ${myMap}">
<td th:text="${instance.key}">key</td>
<td th:each="listObject : ${instance.value}">
<th:block th:text="${listObject}">List object text</th:block>
</td>
</tr>
</table>
Vertical display:
<table cellspacing='0'>
<th:block th:each="instance: ${myMap}">
<tr th:each="listObject, iterStat : ${instance.value}">
<td>
<th:block th:if="${iterStat.index} == 0" th:text="${instance.key}"/>
</td>
<td th:text="${listObject}"></td>
</tr>
</th:block>
</table>
As a reference for the iterStat properties, see: http://www.thymeleaf.org/doc/tutorials/2.1/usingthymeleaf.html#keeping-iteration-status
Upvotes: 7