'Why is Thymeleaf only showing the last line of the list?

I want to get each value from the listAppointments and add it to appointments. Now I want to add each of that value to a model but Thymeleaf is showing only the last value. What should I do?

@GetMapping("/appointmenttoday")
public String appointmentToday(Model model) {
       ZoneId defaultZoneId = ZoneId.systemDefault();
       LocalDate currentDate = LocalDate.now();
       List<Appointments> listAppointments = appointmentsRepository.findAll();
       for(int i = 0; i < listAppointments.size(); i++) {
           Appointments appointments = listAppointments.get(i);
           LocalDate currentDate1 = appointments.toDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
           if(currentDate.compareTo(currentDate1) == 0) {
                model.addAttribute("listAppointments", appointments);
           }
       }
        
return "appointmenttoday";
}

Thymeleaf:

<tbody> 
    <tr th:each="appointment: ${listAppointments}">
        <td th:text="${appointment.appointmentNumber}">Appointment Number</td>
    </tr>
<tbody>


Solution 1:[1]

You are adding the listAppointments model attribute over and over again as a single Appointments object. You should make a new list and then add the desired elements to that list and then you should put that list to model.

@GetMapping("/appointmenttoday")
public String appointmentToday(Model model) {
    ZoneId defaultZoneId = ZoneId.systemDefault();
    LocalDate currentDate = LocalDate.now();
    List<Appointments> listAppointments = appointmentsRepository.findAll();
    List<Appointments> result = new List<Appointments>();
    for(int i = 0; i < listAppointments.size(); i++) {
        Appointments appointments = listAppointments.get(i);
        LocalDate currentDate1 = appointments.toDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
        if(currentDate.compareTo(currentDate1) == 0) {
           result.add(appointments);
        }
    }

    model.addAttribute("listAppointments", result);        
    return "appointmenttoday";
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ahmet