Search code examples
spring-mvcthymeleaf

thymeleaf th:each use increasing variable as list index


I have a class course which has a list of attendees.

public class course {

    private List<Address> attendeeList;

    public List<Address> getAttendeeList() {
        return attendeeList;
    }

}

If I edit an existing course, I want the select fields to autoselect the option of the correct attendee. Below is an excerpt of my html page:

<p class="form-control-static" th:each="i, stat : ${course.attendeeList}"> 
   <select class="form-control" name="attendeeIds">
      <option th:value="0">Please select an Attendee</option>
      <option th:each="attendee : ${addresses}" 
         th:value="${attendee.id}" 
         th:text="${attendee.firstName}+' '+${attendee.lastName}" 
         th:selected="${attendee.id}==
            (course.attendeeList[${stat.index}].id})"> 
      </option>
   </select>
</p>

If I open the page I get the following error: Unexpected token. Expected 'rsquare(])' but was 'lcurly({)'

If I replace ${stat.index} with a number for example 0 and my course has 10 attendees, then the select item appears 10 times but always with the first member selected. How can I select the correct attendee in each select field?


Solution

  • Try changing from:

    (course.attendeeList[${stat.index}].id})"> 
    

    to:

    (course.attendeeList[__${stat.index}__].id})">