【问题标题】:Nested loop in ThymeleafThymeleaf 中的嵌套循环
【发布时间】:2022-04-25 16:25:58
【问题描述】:

我是 Thymeleaf 的新手。

我有两个对象 - ClassroomStudent:每个教室都包含一个 List<Student>,我可以有一个教室列表:List<Classroom>

我想用 Thymeleaf 做的就是下面的 java 代码:

            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));
                }
            }

所以输出将是:{classroom1{joe1,joe2}, classroom2{joe3}}...

但我需要能够在 HTML 中使用 Thymeleaf(通过传递教室列表)来实现这一点,这样我才能让它看起来不错。

非常感谢任何帮助。谢谢!

【问题讨论】:

  • 请注意,这在 Java 中是不好的做法,因为它过于复杂,而且get() 可能是 O(n)。在 Java 和 Thymeleaf 中,您都需要一个迭代器;在后一种情况下,您正在寻找th:each

标签: java html html-lists thymeleaf


【解决方案1】:

使用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>

【讨论】:

  • 正是我需要的!谢谢!
  • "${classroom.name}"
    。应该是
  • @Arun 你是对的。我改进了答案!
猜你喜欢
  • 1970-01-01
  • 2018-05-06
  • 2015-03-29
  • 1970-01-01
  • 2021-01-27
  • 2015-06-05
  • 2015-11-22
  • 2022-01-21
  • 2011-01-20
相关资源
最近更新 更多