Thymeleaf遍历标签
- 方法
@GetMapping("/")
public ModelAndView main() {
List<User> users = Arrays.asList(
new User().setId(1L).setUsername("张三"),
new User().setId(2L).setUsername("李四"),
new User().setId(3L).setUsername("王五"),
new User().setId(4L).setUsername("小明")
);
ModelAndView modelAndView = new ModelAndView("/index");
modelAndView.addObject("lists", users);
return modelAndView;
}
- 页面
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>首页</title>
</head>
<body>
<div>
<h4>完整展示</h4>
<table border="1">
<tr>
<th>序号</th>
<th>下标</th>
<th>ID</th>
<th>用户名</th>
</tr>
<tr th:each="user, userStat:${lists}">
<td th:text="|序号:${userStat.count}|"/>
<td th:text="|下标:${userStat.index}|"/>
<td th:text="${user.id}"/>
<td th:text="${user.username}"/>
</tr>
</table>
</div>
<br/>
<div>
<h4>展示指定范围内的数据(第二条到最后一条【跳过第一条】)</h4>
<table border="1">
<tr>
<th>序号</th>
<th>下标</th>
<th>ID</th>
<th>用户名</th>
</tr>
<tr th:each="user, userStat:${lists}">
<block th:if="${userStat.index lt userStat.size and userStat.index gt 0}">
<td th:text="|序号:${userStat.count}|"/>
<td th:text="|下标:${userStat.index}|"/>
<td th:text="${user.id}"/>
<td th:text="${user.username}"/>
</block>
</tr>
</table>
</div>
</body>
</html>
效果
-
th:each="p,status: ${ps},
status`里还包含了如下信息:-
index
属性, 0 开始的索引值 -
count
属性, 1 开始的索引值 -
size
属性, 集合内元素的总量 -
current
属性, 当前的迭代对象 -
even/odd
属性, boolean 类型的, 用来判断是否是偶数个还是奇数个 -
first
属性, boolean 类型, 是否是第一个 -
last
属性, boolean 类型, 是否是最后一个
-
-
判断表达式
表达式 | 说明 |
---|---|
gt | great than(大于)> |
ge | great equal(大于等于)>= |
eq | equal(等于)== |
lt | less than(小于)< |
le | less equal(小于等于)<= |
ne | not equal(不等于)!= |