简体   繁体   English

如何在Thymeleaf中显示每个循环的对象集合?

[英]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. 我想用Spring MVC在浏览器中显示数据库中的数据。 Everything is alright, except my Thymeleaf template for each loop. 一切都没问题,除了每个循环的Thymeleaf模板。 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? 如何在ID行中显示id数据,在Name行中显示name数据,迭代每个循环的对象集合?

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>

Your question is not very clear, as you didn't specify your count object, and didn't show your controller. 你的问题不是很明确,因为你没有指定你的count对象,也没有显示你的控制器。

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. 假设您有一些具有字段idname实体Count ,您将其保存在数据库的相应表中,并且您希望在Thymeleaf模板中显示该实体。

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() : 要从数据库中检索数据,您需要一些ServiceRepository类,它应该具有返回实体List的方法,例如此类服务方法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. 然后,您需要在控制器中设置请求映射 ,并在该方法中添加一个属性到model对象,这将是执行listAll()方法的结果。 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: 最后回答您的问题,您的list.html模板应该包含块:

<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. 阅读Thymeleaf文档 - 迭代基础知识部分中的更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM