Search code examples
javascripthtmlthymeleaf

Nested for loop in HTML table


I am trying to create a table that is created from Lists of different sizes. I have a list of Cars List<Car>. So in the header I want to place the names of the different companies which I did.

Then I have a List<List<CarSales>> and not all Cars exist in each carSales. So I want to iterate through the List of List of each tr (also OK) and then I want to iterate in the td though the List and place the CarSales.sales in the correct td where CarSales.mark=Car.makr of the header.

So if List<Cars> is (I mean Cars.mark)

[BMW, MERCEDES,FIAT]

And List<List<CarSales>> is (I mean object that have mark and sales inside)

[[BMW:5,FIAT:10],[MERCEDES:12]]

I want a table with:

BMW - MERCEDES - FIAT

 5  -    0     -  10

 0  -   12     -  0

Solution

  • You might be able to do that... but you can make the markup so much simpler if List<List<CarSales>> was instead a List<Map<String, Integer>> instead (where the key is the mark, and the value is the sales). Then you could have something like this:

    <table>
      <tr>
        <th th:each="car: ${cars}" th:text="${car.mark}" />
      </tr>
    
      <tr th:each="sale: ${carSales}">
        <td th:each="car: ${cars}" th:text="${sale.get(car.mark)} ?: 0" />
      </tr>
    </table>
    

    If you want to go with your original structure, something like this might work, but it's more confusing to maintain:

    <table>
      <tr>
        <th th:each="car: ${cars}" th:text="${car.mark}" />
      </tr>
    
      <tr th:each="sales: ${carSales}">
        <td th:each="car: ${cars}" th:with="sale=${sales.^[mark==#root.car.mark]}" th:text="${sale?.sales} ?: 0" />
      </tr>
    </table>