新闻资讯

质量为本、客户为根、勇于拼搏、务实创新

< 返回新闻资讯列表

thymeleaf循环遍历的有哪些方法,foreach循环遍历

发布时间:2024-02-05 16:30:45

thymeleaf循环遍历的有哪些方法

Thymeleaf提供了多种循环遍历的方法,以下是经常使用的几种方法:

  1. 使用th:each指令:使用th:each指令可以循环遍历一个集合,并将集合中的每一个元素绑定到当前迭代的变量上。例如:
<ul>
    <li th:each="item : ${items}" th:text="${item}"></li>
</ul>
  1. 使用th:each指令的索引变量:除绑定集合中的元素,还可使用th:each指令的索引变量来获得当前迭代的索引值。例如:
<ul>
    <li th:each="item, index : ${items}" th:text="${index + 1 + '. ' + item}"></li>
</ul>
  1. 使用th:each指令的状态变量:可使用th:each指令的状态变量来获得当前迭代的状态信息。例如:
<table>
    <tr th:each="user, status : ${users}">
        <td th:text="${status.index + 1}"></td>
        <td th:text="${user.name}"></td>
        <td th:text="${status.current}"></td>
        <td th:text="${status.first}"></td>
        <td th:text="${status.last}"></td>
    </tr>
</table>
  1. 使用th:block指令:可使用th:block指令将要循环的内容包裹起来,然后使用th:each指令在th:block内进行循环。例如:
<th:block th:each="item : ${items}">
    <p th:text="${item}"></p>
</th:block>

这些都是Thymeleaf中经常使用的循环遍历方法,可以根据具体的需求选择适合的方法来进行循环遍历。