0

I have a user class with a List of Meals inside this class. I'm wondering, how to iterate through all users and meals inside each user to get an effect like this below:

Effect

User class:

@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;

    // ...
}

I now, how to iterate through users, but can't imagine how

<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>
Vicardo
  • 61
  • 8
  • Does this answer your question? [Thymeleaf iteration over list of objects](https://stackoverflow.com/questions/32599395/thymeleaf-iteration-over-list-of-objects) – Nikolay Shebanov Dec 24 '20 at 12:42
  • 1
    You can add a `th:each="meal : ${user.meals}"` iterator inside your users iterator. See the final section of [this answer](https://stackoverflow.com/a/61146286/12567365) where there is a Thymeleaf example showing this double-iteration structure. – andrewJames Dec 24 '20 at 14:48
  • Also, Thymeleaf can refer to field names instead of methods - assuming you have your fields and getters named correctly. So, you can replace `${user.getUsername()}` with `${user.username}`, which is cleaner. – andrewJames Dec 24 '20 at 14:49

1 Answers1

0

You can iterate user list in outer loop and meals inside inner loop during every user object iteration like below.

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

Note: To get exact table structure you might have to use html colspan attribute properties.

Alien
  • 15,141
  • 6
  • 37
  • 57
  • Unfortunately, it doesn't work. The second loop can't see the "user" variable from the first loop – Vicardo Dec 29 '20 at 13:18