Spring Boot中Thymeleaf如何同时遍历三个相同长度的JPA实体列表
方案1:后端封装统一传输对象(推荐)
这种方式更符合MVC分层规范,也避免模板层处理过多业务逻辑,降低出错概率。
- 首先新建一个组合封装类:
// 可放在项目的dto或entity包下 public class AbcCombination { private ATable a; private BTable b; private CTable c; // 全参构造方法 public AbcCombination(ATable a, BTable b, CTable c) { this.a = a; this.b = b; this.c = c; } // 补充getter方法 public ATable getA() {return a;} public BTable getB() {return b;} public CTable getC() {return c;} }
- 控制器中组装后传入model:
// 原有查询三个列表的逻辑保持不变 List<ATable> atables = atableRepository.findAll(); List<BTable> btables = btableRepository.findAll(); List<CTable> ctables = ctableRepository.findAll(); // 组装组合对象列表 List<AbcCombination> combinations = new ArrayList<>(); for (int i = 0; i < atables.size(); i++) { combinations.add(new AbcCombination(atables.get(i), btables.get(i), ctables.get(i))); } model.addAttribute("combinations", combinations);
- 模板中直接遍历单列表即可实现需求:
<div th:each="combo : ${combinations}"> <p th:text="${combo.a.acontent}"></p> <p th:text="${combo.b.bcontent}"></p> <p th:text="${combo.c.ccontent}"></p> <hr/> </div>
方案2:模板层直接通过索引遍历(无需修改后端代码)
如果不想调整后端逻辑,可以直接利用Thymeleaf遍历的内置状态变量获取当前索引,再通过索引取另外两个列表对应位置的元素,使用前提是保证三个列表长度完全一致:
<div th:each="a, stat : ${atables}"> <p th:text="${a.acontent}"></p> <p th:text="${btables[__${stat.index}__].bcontent}"></p> <p th:text="${ctables[__${stat.index}__].ccontent}"></p> <hr/> </div>
上述代码中的stat是Thymeleaf遍历的内置状态对象,stat.index代表当前遍历的索引值(从0开始计数),__${}__是预处理表达式,会先把索引值解析出来再作为列表下标完成取值。
内容的提问来源于stack exchange,提问作者Edoardo Fiorini
相关产品推荐
相关产品推荐

