Reputation: 27
I am creating a project in eclipse where I want to display values input into a form in a table. I want the table to only display the rows which have values, but cannot work out how to do this. So far I have just added multiple rows and am using display:none
in order to not display them, but I do not cannot think of a way to get the th:text="${name1}"
to display.
Here is an example of the way I am doing it so far:
<table id="table">
<tr id="tableRow">
<th class="tableHeader">Name</th>
<th class="tableHeader">Description</th>
</tr>
<tr id="tableRow" style="display:none">
<td class="tableCell" th:text="${name1}"></td>
<td class="tableCell" th:text="${description1}"></td>
</tr>
<tr id="tableRow" style="display:none">
<td class="tableCell" th:text="${name2}"></td>
<td class="tableCell" th:text="${description2}"></td>
</tr>
<tr id="tableRow" style="display:none">
<td class="tableCell" th:text="${name3}"></td>
<td class="tableCell" th:text="${description3}"></td>
</tr>
</table>
I am relatively new to coding and so any help would be appreciated.
Upvotes: 1
Views: 2360
Reputation: 27
I found a good way to do it using th:each
:
<table id="table">
<tr id="tableRow">
<th class="tableHeader">Name</th>
<th class="tableHeader">Description</th>
</tr>
<tr id="tableRow" th:each="inputMap : ${InputMap}">
<td class="tableCell" th:text="${inputMap.value.name}"></td>
<td class="tableCell" th:text="${inputMap.value.description}"></td>
</tr>
</table>
The ${InputMap}
comes from my controller:
@GetMapping("/tablePage")
public void getTableData(Model model) {
inputRepository.findAll().forEach(inputObject -> {
inputMap.put(inputObject.id, inputObject);
});
if (inputMap != null){
inputMap.forEach((id, i) -> {
model.addAttribute(id + "name", id + i.getName());
model.addAttribute(id + "description", id + i.getDescription());
});
}
model.addAttribute("InputMap", inputMap);
}
Upvotes: 0
Reputation: 11
you need to test values before consuming it
<table id="table">
<tr id="tableRow">
<th class="tableHeader">Name</th>
<th class="tableHeader">Description</th>
</tr>
<tr id="tableRow" th:if="${name1 != null or description1 != null}">
<td class="tableCell" th:text="${name1}"></td>
<td class="tableCell" th:text="${description1}"></td>
</tr>
<tr id="tableRow" th:if="${name2 != null or description2 != null}">
<td class="tableCell" th:text="${name2}"></td>
<td class="tableCell" th:text="${description2}"></td>
</tr>
<tr id="tableRow" th:if="${name3 != null or description3 != null}">
<td class="tableCell" th:text="${name3}"></td>
<td class="tableCell" th:text="${description3}"></td>
</tr>
</table>
Upvotes: 1