Thymeleaf的th:each和th:if如何正确运用?

2026-05-21 11:491阅读0评论SEO问题
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计483个文字,预计阅读时间需要2分钟。

Thymeleaf的th:each和th:if如何正确运用?

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

示例:Controller 代码java@Controllerpublic class HelloController { @RequestMapping(/success) public String success(Map map) { map.put(users, Arrays.asList(Alice, Bob, Charlie)); }}

一、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="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

Thymeleaf的th:each和th:if如何正确运用?

注意: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为真的时候,显示本句话,这是用三相表达式做的':''" >

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

本文共计483个文字,预计阅读时间需要2分钟。

Thymeleaf的th:each和th:if如何正确运用?

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

示例:Controller 代码java@Controllerpublic class HelloController { @RequestMapping(/success) public String success(Map map) { map.put(users, Arrays.asList(Alice, Bob, Charlie)); }}

一、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="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

Thymeleaf的th:each和th:if如何正确运用?

注意: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为真的时候,显示本句话,这是用三相表达式做的':''" >

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