用到的标签和函数
numbers.sequence(from,to)函数
生成一个从from到to的序列;
th:with
定义局部变量,可以配合td:block标签使用,也可以定义在常规html标签内;
th:block
功能标签,标签本身不会输出为一个html元素,只是用来做取值、赋值、循环等功能性用途。
th:each
用于遍历数组,具体说明详见 thymeleaf 动态生成表格
th:if
用做逻辑判断,满足条件则输出html,不满足则不输出。
示例代码
通过userList数组生成一个表格,表格的每一行不超过5个元素(最后一行可能少于5个):
<!--
用 th:with 定义局部变量 colSize 和 rowSize , 变量作用域在它所在的 table 之内。
colSize=5 表示每行显示5五个,超过则换行,
rowSize 行数,通过userList的总数和colSize计算出来。
-->
<table border="1" th:with="colSize=${5}, rowSize=${userList.size()/colSize}, rowSize=${(userList.size()%colSize==0 ? rowSize : (rowSize+1))}">
<!--遍历行数,rowIdx为行号,每一行是一个tr标签对 -->
<tr th:if="${userList.size() gt 0}" th:each="rowIdx:${#numbers.sequence(1, rowSize)}">
<!--遍历列数,colIdx为列号,每一列是一个td标签对 -->
<td th:each="colIdx:${#numbers.sequence(1,colSize)}">
<!-- 根据行号和列号计算数组的下标索引号idx ,然后通过idx从userList中取出一个元素user
由于最后一行的数据可能没有满行(userList.size()%colSize!=0的情况),因此需要做数组越界判断, -->
<!-- th:block 功能标签,标签本身不会输出为一个html元素,此处只是用来配合 th:with -->
<th:block th:with="idx=${(rowIdx-1)*colSize+colIdx-1}, user=${idx<userList.size() ? userList[idx] : null}">
<!-- th:if 决定是否输出 input 标签:user不是空指针才输出 -->
<input th:if="${user ne null}" name="userList" type="checkbox" th:value="${user.id}" th:text="${user.nickname}"/>
</th:block>
</td>
</tr>
</table>
效果
每行不超过5个元素: