How can i iterate two listings at the same time using the thymeleaf th:each.
<select id="rooms" th:field="*{room}">
<option th:each="room : ${roomsFromHotel}"
th:value="${{room}}"
th:text="${room.id}">
room name
</option>
</select>
This is working, but i would like to do something like this
<select id="rooms" th:field="*{room}">
<option th:each="room : ${roomsFromHotel}, roomType : ${roomTypesList}"
th:value="${{room}}"
th:text="${roomType.name}">
room name
</option>
</select>
Unfortunately you cannot do it that way.
Two options that I can think of right now:
If the lists are of equal size and indexes correspond to same object, put them in a Map and iterate the map. That way you will get the room and roomType
(Preferred) Create a object and save the room and roomType in it, then add it to single List and iterate the list.
I prefer the second method because you can guarantee what you are actually passing into the list and onto the view layer for processing.
To expand on @Aeseir answers second option, I figured out it would be good idea to create inner class inside controller method with room and roomType. That way you don't pile up project structure, and have single use object, which is desirable in this case.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With