如何在Thymeleaf表格中实现每行显示5条数据的迭代循环?
问题
现有100条产品数据,当前使用以下Thymeleaf代码实现每行显示1条产品,呈垂直排列:
<table> <tr th:each="product : ${data}"> <td> <input type="checkbox" name="productCode" th:value="${product.productCode}" th:text="${product.productName}" /> </td> </tr> </table>
需要修改为每行显示5条产品,满5条后换行,如何通过迭代器实现该需求?
解决方案
可以借助Thymeleaf迭代器的stat状态对象,通过索引判断来控制行的生成,以下是可靠的实现方式:
<table> <!-- 仅在索引为5的倍数时创建新行 --> <tr th:each="product, stat : ${data}" th:if="${stat.index % 5 == 0}"> <!-- 循环生成当前行的5个单元格,同时避免索引越界 --> <td th:each="offset : ${#numbers.sequence(0, 4)}" th:if="${stat.index + offset < data.size()}"> <input type="checkbox" name="productCode" th:value="${data[stat.index + offset].productCode}" th:text="${data[stat.index + offset].productName}" /> </td> </tr> </table>
关键逻辑说明:
stat.index:获取当前迭代元素的起始索引(从0开始)stat.index % 5 == 0:当索引是5的倍数时,触发新行的创建#numbers.sequence(0, 4):生成0到4的偏移量,对应一行的5个产品位置stat.index + offset < data.size():防止最后一行因产品数量不足5个导致索引越界
如果偏好从1开始计数的逻辑,也可以用stat.count(从1开始)来判断:
<table> <tr th:each="product, stat : ${data}" th:if="${stat.count % 5 == 1}"> <td th:each="i : ${#numbers.sequence(0, 4)}" th:if="${stat.count + i -1 <= data.size()}"> <input type="checkbox" name="productCode" th:value="${data[stat.count + i -2].productCode}" th:text="${data[stat.count + i -2].productName}" /> </td> </tr> </table>
不过第一种基于stat.index的写法逻辑更直观,更易维护。
内容的提问来源于stack exchange,提问作者HOO
相关产品推荐
相关产品推荐

