Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thymeleaf th:each two iterate two listings

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>
like image 754
Miguel Morujão Avatar asked Nov 20 '15 16:11

Miguel Morujão


2 Answers

Unfortunately you cannot do it that way.

Two options that I can think of right now:

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

  2. (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.

like image 144
Aeseir Avatar answered Oct 19 '22 02:10

Aeseir


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.

like image 2
Kolos Avatar answered Oct 19 '22 03:10

Kolos