zoukankan      html  css  js  c++  java
  • thymeleaf——th:each、th:if的使用

    一、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为真的时候,显示本句话,这是用三相表达式做的':''" ></p>
  • 相关阅读:
    在CentOS 8 上 部署 .Net Core 应用程序
    Asp.Net Core 查漏补缺《一》 —— IStartFilter
    接口相关数据日志打印
    退款
    识别身份证
    生成二维码
    打造一款简单易用功能全面的图片上传组件
    Redis过期策略+缓存淘汰策略
    Redis主从复制
    .net 平台常用框架
  • 原文地址:https://www.cnblogs.com/bear7/p/13490020.html
Copyright © 2011-2022 走看看