thymeleaf中的th:each用法

一.th:eath迭代集合用法:

复制代码
<table>
        <thead>
            <tr>
                <th>序号</th>
                <th>用户名</th>
                <th>密码</th>
                <th>用户昵称</th>
            </tr>
            <tr th:each="user:${userlist}">
                <td th:text="${user.id}"></td>
                <td th:text="${user.username}"></td>
                <td th:text="${user.password}"></td>
                <td th:text="${user.petname}"></td>
            </tr>
        </thead>
    


</table>
复制代码

二.迭代下标变量用法:

  状态变量定义在一个th:每个属性和包含以下数据:

  1.当前迭代索引,从0开始。这是索引属性。index

  2.当前迭代索引,从1开始。这是统计属性。count

  3.元素的总量迭代变量。这是大小属性。 size 

  4.iter变量为每个迭代。这是目前的财产。 current 

  5.是否当前迭代是奇数还是偶数。这些even/odd的布尔属性。  

  6.是否第一个当前迭代。这是first布尔属性。  

  7.是否最后一个当前迭代。这是last布尔属性。

用法实例:

  

复制代码
<table>
        <thead>
            <tr>
                <th>序号</th>
                <th>用户名</th>
                <th>密码</th>
                <th>用户昵称</th>
            </tr>
            <tr th:each="user,userStat:${userlist}" th:class="${userStat.odd}?'odd':'even'">
                <td th:text="${user.id}"></td>
                <td th:text="${user.username}"></td>
                <td th:text="${user.password}"></td>
                <td th:text="${user.petname}"></td>
            </tr>
        </thead>
    </table>
复制代码

打印出status的值为:

如果你不显式地设置迭代变量,Thymeleaf总是会为您创建一个统计的名字作为后缀iter变量:

复制代码
<table>
  <tr>
    <th>NAME</th>
    <th>PRICE</th>
    <th>IN STOCK</th>
  </tr>
  <tr th:each="prod : ${prods}" th:class="${prodStat.odd}? 'odd'">
    <td th:text="${prod.name}">Onions</td>
    <td th:text="${prod.price}">2.41</td>
    <td th:text="${prod.inStock}? #{true} : #{false}">yes</td>
  </tr>
</table>
复制代码
原文地址:https://www.cnblogs.com/roak/p/14705887.html