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>
  • 相关阅读:
    前沿技术解密——VirtualDOM
    Ques核心思想——CSS Namespace
    Unix Pipes to Javascript Pipes
    Road to the future——伪MVVM库Q.js
    聊聊CSS postproccessors
    【译】十款性能最佳的压缩算法
    Kafka Streams开发入门(9)
    Kafka Streams开发入门(8)
    【译】Kafka Producer Sticky Partitioner
    【译】99th Percentile Latency at Scale with Apache Kafka
  • 原文地址:https://www.cnblogs.com/bear7/p/13490020.html
Copyright © 2011-2022 走看看