thymeleaf

How to filter a collection in thymeleaf th:each according to a Date


folks... I have a problem filtering a date in a th:each iteration. I populate a List like that:

    List<Date> days = new ArrayList<>();
    
    days.add( new Date(2024,11,10) );
    days.add( new Date(2024,12,05) );
    
    model.addAttribute("days", days);

And populate another object with my appointments from a database:

    List<oCalendar> calendaries = myRepository.findAppointmentBeginEnd(dateBegin, dateEnd);
    model.addAttribute("calendaries", calendaries);

Now, I need to filter in another th:each that values:

   <tr th:each="day : ${days}" scope="col" >
       <tr th:each="cal : ${calendaries.?[dateAppointment eq __${#dates.format(day, 'dd/MM/yyyy')}__]}">
          <td th:text="${cal.dateAppointment}"></td>
          <td th:text="${cal.hourAppointment}"></td>
       </tr>
   </tr>

But I don't succeed... I tried many variants

${calendaries.?[dateAppointment eq __${#dates.format(day, 'dd/MM/yyyy')}__]}
${calendaries.?[dateAppointment eq __${day}__]}
${calendaries.?[dateAppointment eq ${day}]}

but none of them worked...

Any help?


Solution

  • Use the #ctx to access other variables in collection selection. Like this:

    <th:block th:each="day : ${days}" scope="col" >
        <tr th:each="cal : ${calendaries.?[dateAppointment eq #ctx.day]}">
            <td th:text="${cal.dateAppointment}"></td>
            <td th:text="${cal.hourAppointment}"></td>
        </tr>
    </th:block>