【问题标题】:Thymeleaf - how to iterate through a list inside a classThymeleaf - 如何遍历类中的列表
【发布时间】:2021-04-02 20:36:36
【问题描述】:

我有一个用户类,该类中有一个膳食列表。我想知道,如何遍历每个用户内部的所有用户和餐食以获得如下效果:

用户类别:

@Entity
@Table(name = "users")
public class User {

    private int id;
    private String username;
    private String password;
    private int age;
    private String email;
    private Gender gender;
    private List<Meal> meals;

    // ...
}

我现在,如何遍历用户,但无法想象如何

<body>

    <table class="table">
        <thead>
            <tr>
                <th>Username</th>
            </tr>
        </thead>
        <tbody>
            <tr th:each="user : ${users}">
                <td th:text="${user.getUsername()}"></td>
            </tr>
        </tbody>
    </table>
</body>

【问题讨论】:

  • 这能回答你的问题吗? Thymeleaf iteration over list of objects
  • 您可以在您的用户迭代器中添加一个th:each="meal : ${user.meals}" 迭代器。请参阅this answer 的最后一部分,其中有一个 Thymeleaf 示例显示了这种双迭代结构。
  • 此外,Thymeleaf 可以引用字段名称而不是方法 - 假设您的字段和 getter 命名正确。所以,你可以把${user.getUsername()}换成${user.username},这样更干净。

标签: java spring spring-boot spring-mvc thymeleaf


【解决方案1】:

您可以在每次用户对象迭代期间在外循环中迭代用户列表,在内循环中迭代餐点,如下所示。

<tr th:each="user : ${users}">
         <td th:text="${user.username}"></td>
         <tr th:each="meal : ${user.meals}">
                <td th:text="${meal.mealName}"></td>
         </tr>
</tr>

注意:要获得准确的表结构,您可能必须使用 html colspan 属性。

【讨论】:

  • 不幸的是,它不起作用。第二个循环看不到第一个循环中的“用户”变量
猜你喜欢
  • 2021-12-09
  • 2018-09-24
  • 1970-01-01
  • 1970-01-01
  • 2019-12-24
  • 2017-12-25
  • 2018-03-08
  • 1970-01-01
相关资源
最近更新 更多