首页 > 编程笔记 > Java笔记 阅读:2

Thymeleaf th:each的用法(附带实例)

循环遍历在日常项目中比较常用,一般用于将后台返回的数据渲染到前端的表格中。Thymeleaf 可以使用 th:each 标签进行数据的迭代循环,语法:
th:each="obj,iterStat:${objList}"
支持 List、Map、数组数据类型等。下面通过简单的例子演示数据循环遍历的过程。

1) 定义后端数据。首先在后端定义一个用户列表,然后传递到前端页面:
@RequestMapping("/list")
public String list(ModelMap map) {
    List<User> list=new ArrayList();
    User user1=new User("spring",12,"123456");
    User user2=new User("boot",6,"123456");
    User user3=new User("Thymeleaf",66,"123456");
    list.add(user1);
    list.add(user2);
    list.add(user3);
    map.addAttribute("users", list);
    return "list";
}
在上面的示例代码中,后台返回 list.html 页面,同时返回 ArrayList 类型的用户列表数据。

2) 创建前台页面。在 templates 目录下创建 list.html 页面,展示后台的数据,示例代码如下:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8"></meta>
    <title>Example switch </title>
</head>
<body>
<h1>Thymeleaf模板引擎</h1>
<h3>each循环遍历</h3>
<div >
    <table>
        <tr>
            <th>姓名</th>
            <th>年龄</th>
            <th>密码</th>
            <th>变量:index</th>
            <th>变量:count</th>
            <th>变量:size</th>
            <th>变量:even</th>
            <th>变量:odd</th>
            <th>变量:first</th>
            <th>变量:last</th>
        </tr>
        <tr th:each="user,stat : ${users}">
            <td th:text="${user.name}">name</td>
            <td th:text="${user.age}">age</td>
            <td th:text="${user.password}">password</td>
            <td th:text="${iterStat.index}">index</td>
            <td th:text="${iterStat.count}">count</td>
            <td th:text="${iterStat.size}">size</td>
            <td th:text="${iterStat.even}">even</td>
            <td th:text="${iterStat.odd}">odd</td>
            <td th:text="${iterStat.first}">first</td>
            <td th:text="${iterStat.last}">last</td>
        </tr>
    </table>
</div>
</body>
</html>

循环遍历通过 th:each 实现,语法:
th:each="obj,stat:${objList}"

在遍历的同时,也可以获取迭代对象的迭代状态变量 stat,它包含如下属性:
3) 运行验证。启动项目,在浏览器中输入地址:http://localhost:8080/list,页面显示效果如下图所示:


图 1 list.html 页面显示效果

由图 1 可知,后端返回的 list 数据被循环遍历并显示在页面中,同时 th:each 标签还提供了 index、count 等标签。

相关文章