Thymeleaf中th:each及th:if使用方法解析

2020-08-31

一、th:each

作用:用于遍历controller层发送过来的集合。

例:

Controller代码:

@Controller
public class HelloController {
  @RequestMapping("/success")
  public String success(Map<String,Object> map){
    map.put("users", Arrays.asList("张三","李四","王五"));
    return "success";
  }
}

下面我们通过th:each属性在html页面将其遍历显示出来

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
  <h4 th:text="${user}" th:each="user:${users}"></h4>
</body>
</html>

讲解:

th:each="user:${users}"

  其中${users}是将取出名为users的List集合,每次遍历取出List集合中的一个元素赋值给user

注意:th:each每次遍历都会生成一个包含它的标签,如我们举的这个例子,users中一共有三个元素,所以会遍历三次,每次都会生成一个h4标签

二、th:if

Thymeleaf 的条件判断是 通过 th:if 来做的,只有为真的时候,才会显示当前元素

<p th:if="${testBoolean}" >如果testBoolean 是 true ,本句话就会显示</p>

取反可以用not, 或者用th:unless.

<p th:if="${not testBoolean}" >取反 ,所以如果testBoolean 是 true ,本句话就不会显示</p>
<p th:unless="${testBoolean}" >unless 等同于上一句,所以如果testBoolean 是 true ,本句话就不会显示</p>

除此之外,三元表达式也比较常见

<p th:text="${testBoolean}?'当testBoolean为真的时候,显示本句话,这是用三相表达式做的':''" >

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持北冥有鱼。

《Thymeleaf中th:each及th:if使用方法解析.doc》

下载本文的Word格式文档,以方便收藏与打印。