【问题标题】:How to display the collection of objects with for each loop in Thymeleaf?如何在 Thymeleaf 中显示每个循环的对象集合?
【发布时间】:2017-09-02 03:06:19
【问题描述】:

我想用 Spring MVC 在浏览器中显示数据库中的数据。一切都很好,除了每个循环的 Thymeleaf 模板。那里出了点问题。

如何在 ID 行中显示 id 数据,在 Name 行中显示 name 数据,并使用 for each 遍历对象集合em> 循环?

源代码:

<!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>

【问题讨论】:

    标签: java spring-mvc thymeleaf


    【解决方案1】:

    您的问题不是很清楚,因为您没有指定 count 对象,也没有显示您的控制器。

    假设您有一些实体Count,其字段为idname,您将其保存在数据库的相应表中,并且您希望将其显示在Thymeleaf 模板中。

    要从数据库中检索数据,您需要一些 ServiceRepository 类,它们应该具有返回实体的 List 的方法,此类服务方法的示例listAll():

    public List<Count> listAll() {
        List<Count> counts = new ArrayList<>();
        countRepository.findAll().forEach(counts::add);
        return counts;
    }
    

    然后您需要在控制器中设置请求映射,并在该方法中为model 对象添加一个属性,这将是执行listAll() 方法的结果。可以这样做:

    @RequestMapping("/list")
    public String countsList(Model model) {
        model.addAttribute("counts", countService.listAll());
        return "list";
    }
    

    终于回答了你的问题,你的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>
    

    在 Thymeleaf 文档 - Iteration Basics 部分阅读更多信息。

    【讨论】:

    • 很抱歉……但你做得很好!这就是我所需要的。非常感谢!
    • 很好地将操作方法​​信息按开始到结束的顺序排列。正是我正在寻找的。尽管我只需要最后一部分,但这是一种非常有用的格式。
    • 如何在 count 中打印一个列表。例如 count.someList
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-04-15
    • 2021-04-11
    • 2019-08-14
    • 1970-01-01
    • 1970-01-01
    • 2015-03-09
    • 2013-01-06
    相关资源
    最近更新 更多