Reputation: 570
i have a list that contains entity classes with two variables (id and categoryname). My entity looks like this:
String categoryName;
int categoryID;
//getters and setters
My controller class returns a List of all categories using
service.findAll();
Normally an iteration over this kind of list is one element at a time. My question is I want to be able to get two elements at a tome from the list to enable me populate the UI, which has two columns. Or in more simpler terms, how can I iterate over two elements at once in a List?
<div class="flex items-center justify-between space-x-3">
<div>
<input type="checkbox" name="category" th:value="${category.id}"> <label th:text="${category.categoryName}">
</div>
<div>
<input type="checkbox" name="category" th:value="${category.id}"> <label th:text="${category.categoryName}">
</div>
</div>
Upvotes: 0
Views: 36
Reputation: 26878
This should probably work:
<th:block th:each="i: ${#numbers.sequence(0, list.size()-1, 2)}">
//Edit: I added -1 to list.size()
<div class="flex items-center justify-between space-x-3">
<div>
<input type="checkbox" name="category" th:value="${list[i].id}">
<label th:text="${list[i].categoryName}">
</div>
<div>
<input type="checkbox" name="category" th:value="${list[i+1].id}">
<label th:text="${list[i+1].categoryName}">
</div>
</div>
</th:block>
You will have to do something if the size of the list is not a multiple of 2, unless you know for sure this will always be the case.
PS: I wonder if maybe it is better to use a normal iteration and use CSS to choose how many columns you show depending on screen width for example.
Upvotes: 1