Search code examples
springspring-mvcthymeleaf

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>

Solution

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