1

I'm a newbie to Thymeleaf.

I have two objects- Classroom & Student: each Classroom contains a List<Student> and I can have a list of classrooms: List<Classroom>.

What I want to be able to do with Thymeleaf is the equivalent of the below java code:

            for(int i = 0; i < classroomList.size(); i++){
                System.out.println(classroomList.get(i).getRoomName());
                for(int x = 0; x < studentList.size(); x++){
                    System.out.println(studentList.get(x));
                }
            }

So the output would be: {classroom1{joe1,joe2}, classroom2{joe3}}...

But I need to be able to do this in HTML with Thymeleaf (by passing a list of classrooms) so I can make it look nice.

Any help is much appreciated. Thanks!

1
  • As a note, this is poor practice in Java both because it's overly complicated and because get() can be O(n). In both Java and Thymeleaf you want an iterator; in the latter case, you're looking for th:each. Commented Sep 26, 2018 at 18:05

1 Answer 1

5

Use th:each:

<div th:each="classroom : ${classroomList}">
    <div th:text="${classroom.name}"></div> 
    <ul>
      <div th:each="student : ${classroom.studentList}">
         <li>"${student.name}"</li>
      </div>
    </ul>
</div>
Sign up to request clarification or add additional context in comments.

3 Comments

Exactly what I needed! Thank you!
<div>"${classroom.name}"</div>. should be <div th:text="${classroom.name}"></div>
@Arun you are right. I improved the answer!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.