如何在Thymeleaf中遍历二维数组且不生成额外外层标签
解决方案
使用Thymeleaf原生的th:block虚拟标签作为外层循环的容器即可,该标签仅用于承载模板逻辑,渲染完成后不会在最终HTML中输出任何多余内容,完美匹配你的需求。
正确实现代码:
<div id="puzzle"> <th:block th:each="row, iter : *{matrix}"> <div th:each="col, iter2: ${row}" th:attr="number=${iter.index * 4 + iter2.index + 1}" th:class="'cell-puzzle row-' + ${iter.index + 1} + ' col-' + ${iter2.index + 1}" th:classappend="${col == 0 ? 'cell-puzzle-zero' : ''}" th:text="${col != 0 ? col : ''}"> </div> </th:block> </div>
说明
- 上述代码已经整合了数字为0的格子逻辑,无需再单独写固定的0元素,如果你需要保留单独写0元素的写法,只需将你原有代码里的
<span>替换为<th:block>即可:
<div id="puzzle"> <th:block th:each="row,iter : *{matrix}" > <div th:each="col, iter2: ${row}" th:attr="number=${iter.index + 1}" th:class="'cell-puzzle row-' + ${iter.index + 1} + ' col-' + ${iter2.index + 1}" th:text="${col}"></div> </th:block> <div number="0" class="cell-puzzle row-4 col-4 cell-puzzle-zero"></div> </div>
- 同一个HTML标签不允许定义重复属性,所以你尝试在同一个div上写两个
th:each会直接触发解析报错,这是HTML语法的基础限制,不是Thymeleaf的功能问题。 th:block是Thymeleaf官方提供的原生逻辑容器,不需要你修改后端数据结构,完全符合你的需求。
内容的提问来源于stack exchange,提问作者uncle bob
相关产品推荐
相关产品推荐

