用到的標籤和函數
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個元素: