Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display the collection of objects with for each loop in Thymeleaf?

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>
like image 690
Just4Fun Avatar asked Apr 06 '17 21:04

Just4Fun


People also ask

How do you break the loop in Thymeleaf?

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.


1 Answers

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.

like image 58
DimaSan Avatar answered Oct 22 '22 23:10

DimaSan