I want to display data from database in the browser with Spring MVC. Everything is alright, except my Thymeleaf template for each loop. Something is wrong there.
How can I display id
data in ID row and name
data in Name row iterating through the collection of objects with for each loop?
Source code:
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Getting Started: Serving Web Content</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<table border="1">
<tr style="font-size: 13">
<td>ID</td>
<td>Name</td>
</tr>
<tr th:each="count : ${id}">
<td><p th:text="${count}" /></td>
<td><p th:text="${name}" /></td>
</tr>
</table>
</body>
</html>
The best solution would be the put this logic in the controller and put the first product of type 'T' in a separate attribute. If that's not possible, another solution would be to write a Thymeleaf extension (or if using Spring a bean) that does this.
Your question is not very clear, as you didn't specify your count
object, and didn't show your controller.
Well supposing you have some entity Count
with fields id
and name
, which you persist in the corresponding table of your database, and which you want to display in the Thymeleaf template.
To retrieve data from the database you need some Service or Repository class, that should have method that returns a List
of your entities, example of such service method listAll()
:
public List<Count> listAll() {
List<Count> counts = new ArrayList<>();
countRepository.findAll().forEach(counts::add);
return counts;
}
Then you you need to set up the request mapping in your controller and add in that method an attribute to the model
object, that will be a result of execution listAll()
method. It may be done like:
@RequestMapping("/list")
public String countsList(Model model) {
model.addAttribute("counts", countService.listAll());
return "list";
}
Finally answering your question, your list.html
template should contain the block:
<div th:if="${not #lists.isEmpty(counts)}">
<h2>Counts List</h2>
<table class="table table-striped">
<tr>
<th>Id</th>
<th>Name</th>
</tr>
<tr th:each="count : ${counts}">
<td th:text="${count.id}"></td>
<td th:text="${count.name}"></td>
</tr>
</table>
</div>
Read more info in Thymeleaf Documentation - Iteration Basics section.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With