Anders Persson
Anders Persson

Reputation: 337

thymeleaf used in Spring, adding a list to iterate over with th:each

I want to use the the th:each construct to create a table of items. I have problems with adding the data to the model. I used this contruct:

        model.addAllAttributes(repository.findByusername(username));

findByusername returns a java.Util.List of object. Then I always only have the last element in the list in the model. I gues that it depends on that the attribute namn is the class name so each addition of a new element in the list overrides the prviously added element.

How can I add each element as a separate attribute to the model and then easily iterate them with th:each?

Upvotes: 0

Views: 1241

Answers (1)

Parth Solanki
Parth Solanki

Reputation: 3448

Your Controller is should be return,

model.addAttribute("usersList", repository.findByusername(username)); 

And your thymeleaf code is should be like,

  <th:block th:each="user : ${usersList}">
      <td th:text="${user.username}">Test</td>
  </th:block>

Upvotes: 2

Related Questions