史上最詳 Thymeleaf 使用教程

前言

操做前建議先參考個人另外一篇博客:玩轉 SpringBoot 2 快速整合 | Thymeleaf 篇 查看如何在SpringBoot 中使用 Thymeleaf。還有一點須要注意的是:模版頁面中的 html 上須要聲明 Thymeleaf 的命名空間,具體代碼以下:javascript

<html xmlns:th="http://www.thymeleaf.org">複製代碼

接下來就能夠開始 Thymeleaf 使用教程了!css

全文介紹 Thymeleaf 是基於 Thymeleaf 3.0.11.RELEASE 版本進行說明的。html

基礎語法

文本標籤 th:text/th:utext

用於文本內容的顯示操做。java

  1. th:text 進行文本替換 不會解析html
  2. th:utext 進行文本替換 會解析html

代碼演示:git

@RequestMapping("/th")
    public String th(Model model){
        String msg = "<h1>我是h1</h1>";
        model.addAttribute("msg",msg);
        return "/course/th";
    }複製代碼

th:text 進行文本替換 不會解析htmlgithub

<p th:text="text標籤:  + ${msg}"></p>複製代碼

結果頁面:web

<p>text標籤:<h1>我是h1</h1></p>複製代碼

遊覽器訪問的效果:在這裏插入圖片描述spring

th:utext 進行文本替換 會解析html數組

<p th:utext="utext標籤: + ${msg}"></p>複製代碼

遊覽器展現效果以下圖:在這裏插入圖片描述使用 + 和 | | 效果是同樣的,以下代碼所示:springboot

<p th:utext="utext標籤: + ${msg}"></p>
<p th:utext="|utext標籤: ${msg}|"></p>複製代碼

字符串拼接

拼接字符串經過 + 或者 | 進行拼接

代碼演示:

@RequestMapping("/th")
    public String th(Model model){
        model.addAttribute("a",1);
        model.addAttribute("b",2);
        return "/course/th";
    }複製代碼

模版頁面:

<p th:text="${a}+${b}"></p>複製代碼

結果頁面:

<p>3</p>複製代碼

---模版頁面:

<p th:text="|${a} ${b}|"></p>複製代碼

結果頁面:

<p>1 2</p>複製代碼

---模版頁面:

<p th:text="${a} > ${b}"></p>複製代碼

結果是:

<p>false</p> 複製代碼

---java代碼:

@RequestMapping("/th")
    public String th(Model model){
        model.addAttribute("flag",true);
        return "/course/th";
    }複製代碼

模版頁面:

<p th:text="!${flag}"></p>複製代碼

結果頁面:

<p>false</p>複製代碼

*{...}和 ${...}表達式

正常狀況下 {...} 和 ${...}是同樣的,可是 {...} 通常和 th:object 進行一塊兒使用來完成對象屬性的簡寫。

代碼演示:

@RequestMapping("/th")
    public String th(Model model){
        User user = new User("ljk",18);
        model.addAttribute("user",user);
        return "/course/th";
    }複製代碼

使用 ${...}操做模版代碼:

<p th:text="${user.name}"></p>
<p th:text="${user.age}"></p>複製代碼

結果頁面:

<p>ljk</p><p>18</p>複製代碼

使用 *{...}操做模版代碼:

<p th:text="*{user.name}"></p>
<p th:text="*{user.age}"></p>複製代碼

結果頁面:

<p>ljk</p><p>18</p>複製代碼

使用 *{...}特有操做模版代碼:

<div th:object="${user}" >
    <p th:text="*{name}"></p>
    <p th:text="*{age}"></p>
</div>複製代碼

結果頁面:

<p>ljk</p><p>18</p>複製代碼
{...}表達式

用於國際化message.properties 屬性讀取定義message.properties 配置文件在這裏插入圖片描述在這裏插入圖片描述

定義國際化處理轉換處理類

@Configuration
public class LocaleResolverConfig {
    @Bean(name="localeResolver")
    public LocaleResolver localeResolverBean() {
        return new SessionLocaleResolver();
    }
}複製代碼

定義國際化處理的controller

@Controller
public class ProductController {
    
    @Autowired
    private LocaleResolver localeResolver;
    private  ProductService productService = new ProductService();
      
    @RequestMapping("/")
    public String useT(Model model,HttpServletRequest request,HttpServletResponse response) {
        //設置訪問用戶信息到session
        request.getSession(true).setAttribute("user", new User("桌前", "明月", "CHINA", null));
        localeResolver.setLocale(request,response,Locale.CHINA);
        return "productList";
    }
}複製代碼

若是沒有定義 messageenUS.properties 和 messagezhCN.properties 會默認取message.properties中的信息若是 Locale = Locale.CHINA 就取 messagezhCN.properties若是 Locale = Locale.US 就取 messageenUS.properties。

模版代碼:

<p th:utext="#{home.welcome(${session.user.name})}">Welcome to our grocery store, Sebastian!</p>複製代碼

訪問controller的路徑的效果:在這裏插入圖片描述

~{...}片斷表達式

這個通常和模版佈局的語法一塊兒使用,具體使用方式請看下面模版佈局的教程。

@{...}連接網址表達式

通常和 th:href、th:src進行結合使用,用於顯示Web 應用中的URL連接。經過@{...}表達式Thymeleaf 能夠幫助咱們拼接上web應用訪問的全路徑,同時咱們能夠經過()進行參數的拼接

代碼演示:

模版代碼:

<img th:src="@{/images/gtvglogo.png}"  />複製代碼

結果頁面:

<img src="/sbe/images/gtvglogo.png">複製代碼

---模版代碼:

<a th:href="@{/product/comments(prodId=${prod.id})}" >查看</a>複製代碼

結果頁面:

<a href="/sbe/product/comments?prodId=2">查看</a>複製代碼

---模版代碼:

<a  th:href="@{/product/comments(prodId=${prod.id},prodId2=${prod.id})}" >查看</a>複製代碼

結果頁面:

<a href="/sbe/product/comments?prodId=2&prodId2=2">查看</a>複製代碼

條件判斷 th:if/th:unless

th:if 當條件爲true則顯示。th:unless 當條件爲false 則顯示。

代碼演示:

java代碼:

@RequestMapping("/thif")
    public String thif(Model model){
        model.addAttribute("flag",true);
        return "/course/thif";
    }複製代碼

模版頁面:

<p th:if="${flag}">if判斷</p>複製代碼

結果頁面:

<p>if判斷</p>複製代碼

---模版頁面:

<p th:unless="!${flag}">unless 判斷</p>複製代碼

結果頁面:

<p>unless 判斷</p>複製代碼

switch

th:switch 咱們能夠經過switch來完成相似的條件表達式的操做。代碼演示:java代碼:

@RequestMapping("/thswitch")
    public String thswitch(Model model){
        User user = new User("ljk",23);
        model.addAttribute("user",user);
        return "/course/thswitch";
    }複製代碼

模版頁面:

<div th:switch="${user.name}">
      <p th:case="'ljk'">User is  ljk</p>
      <p th:case="ljk1">User is ljk1</p>
</div>複製代碼

結果頁面:

<div><p> User is ljk</p></div>複製代碼

for循環

th:each 遍歷集合

代碼演示:java代碼:

@RequestMapping("/theach")
    public String theach(Model model){
        
        List<User> userList = new ArrayList<User>();
        User user1 = new User("ljk",18);
        User user2 = new User("ljk2",19);
        User user3 = new User("ljk3",20);
        User user4 = new User("lj4",21);
        userList.add(user1);
        userList.add(user2);
        userList.add(user3);
        userList.add(user4);
        model.addAttribute("userList",userList);
        
        List<String> strList = new ArrayList<String>();
        strList.add("ljk");
        strList.add("ljk2");
        strList.add("ljk3");
        strList.add("lj4");
        model.addAttribute("strList",strList);
        
        return "/course/theach";
}複製代碼

模版頁面:

<table>
      <thead>
        <tr>
          <th>用戶名稱</th>
          <th>用戶年齡</th>
        </tr>
      </thead>
      <tbody>
        <tr th:each="user : ${userList}" th:class="${userStat.odd}? 'odd'">
          <td th:text="${user.name}">Onions</td>
          <td th:text="${user.age}">2.41</td>
        </tr>
      </tbody>
    </table>
----------------------------------------------------------------------
    <table>
      <thead>
        <tr>
          <th>用戶名稱</th>
        </tr>
      </thead>
      <tbody>
        <tr th:each="str : ${strList}" th:class="${strStat.odd}? 'odd'">
          <td th:text="${str}">Onions</td>
        </tr>
      </tbody>
    </table>
複製代碼

結果頁面:在這裏插入圖片描述

咱們能夠經過便利的變量名+Stat 來獲取索引 是不是第一個或最後一個等。便利的變量名+Stat稱做狀態變量,其屬性有:

  • index:當前迭代對象的迭代索引,從0開始,這是索引屬性;
  • count:當前迭代對象的迭代索引,從1開始,這個是統計屬性;
  • size:迭代變量元素的總量,這是被迭代對象的大小屬性;
  • current:當前迭代變量;
  • even/odd:布爾值,當前循環是不是偶數/奇數(從0開始計算);
  • first:布爾值,當前循環是不是第一個;
  • last:布爾值,當前循環是不是最後一個
    *
    for循環介紹內容參考了 CSDN博主liubin5620 Thymeleaf模板引擎經常使用屬性之 th:each迭代循環:https://blog.csdn.net/liubin5620/article/details/80470619

th:href

用於聲明在a 標籤上的href屬性的連接 該語法會和@{..} 表達式一塊兒使用。

代碼演示:java代碼:

@RequestMapping("/thhref")
    public String thhref(Model model){
        return "/course/thhref";
    }複製代碼

模版代碼:

<a href="../home.html" th:href="@{/}">返回首頁</a>複製代碼

結果頁面:

<a href="/sbe/">返回首頁</a>複製代碼

th:class

用於聲明在標籤上class 屬性信息。

代碼演示:java代碼:

@RequestMapping("/thclass")
    public String thclass(Model model){
        return "/course/thclass";
    }複製代碼

模版頁面:

<p th:class=" 'even'? 'even' : 'odd'" th:text=" 'even'? 'even' : 'odd'"></p>複製代碼

結果頁面:

<p class="even">even</p>複製代碼

th:attr

用於聲明html中或自定義屬性信息。

代碼演示:

java代碼:

@RequestMapping("/thattr")
public String thattr(Model model){
    return "/course/thattr";
}複製代碼

模版頁面:

<img  th:attr="src=@{/images/gtvglogo.png}" />複製代碼

結果頁面:

<img src="/sbe/images/gtvglogo.png">複製代碼

th:value

用於聲明html中value屬性信息。

代碼演示:java代碼:

@RequestMapping("/thvalue")
public String thvalue(Model model){
  model.addAttribute("name", "ljk");
  return "/course/thvalue";
}複製代碼

模版頁面:

<input type="text" th:value="${name}" />複製代碼

結果頁面:

<input type="text" value="ljk">複製代碼

th:action

用於聲明html from標籤中action屬性信息。

代碼演示:java代碼:

@RequestMapping("/thaction")
  public String thaction(Model model){
  return "/course/thaction";
}複製代碼

模版頁面:

<form action="subscribe.html" th:action="@{/subscribe}">
        <input type="text" name="name" value="abc"/>
    </form>複製代碼

結果頁面:

<form action="/sbe/subscribe">
        <input type="text" name="name" value="abc">
    </form>複製代碼

th:id

用於聲明htm id屬性信息。

代碼演示:java代碼:

@RequestMapping("/thid")
    public String thid(Model model){
        model.addAttribute("id", 123);
        return "/course/thid";
    }複製代碼

模版頁面:

<p th:id="${id}"></p>複製代碼

結果頁面:

<p id="123"></p>複製代碼

th:inline

JavaScript內聯 操做使用的語法,具體請參考下面內聯操做相關介紹

th:onclick

用於聲明htm 中的onclick事件。

代碼演示:java代碼:

@RequestMapping("/thonclick")
public String honclick(Model model){
  return "/course/thonclick";
}複製代碼

模版頁面:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
    function showUserInfo(){
        alert("i am zhuoqianmingyue!")
    }
</script>
</head>
<body>
   <p th:onclick="'showUserInfo()'">點我</p>
</body>
</html>複製代碼

結果頁面:

<p onclick="showUserInfo()">點我</p>複製代碼

th:selected

用於聲明htm 中的selected屬性信息。

代碼演示:java代碼:

@RequestMapping("/thselected")
    public String thselected(Model model){
        model.addAttribute("sex", 1);
        return "/course/thselected";
    }複製代碼

模版頁面:

<select>
    <option name="sex"></option>
    <option th:selected="1 == ${sex}">男</option>
    <option th:selected="0 == ${sex}">女</option>
</select>複製代碼

結果頁面:

<select>
<option name="sex"></option>
    <option selected="selected">男</option>
    <option>女</option>
</select>複製代碼

th:src

用於聲明htm 中的img中src屬性信息。

代碼演示:java代碼:

@RequestMapping("/thsrc")
public String thsrc(Model model){
    return "/course/thsrc";
}複製代碼

模版頁面:

<img  title="GTVG logo" th:src="@{/images/gtvglogo.png}" />複製代碼

結果頁面:

<img title="GTVG logo" src="/sbe/images/gtvglogo.png">複製代碼

th:style

用於聲明htm中的標籤 css的樣式信息。

代碼演示:java代碼:

RequestMapping("/thstyle")
public String thstyle(Model model){
  model.addAttribute("isShow", true);
  return "/course/thstyle";
}複製代碼

模版頁面:

<p th:style="'display:' + @{(${isShow} ? 'none' : 'block')} + ''"></p>複製代碼

結果頁面:

<p style="display:none"></p>複製代碼

th:with

用於thymeleaf 模版頁面中局部變量定義的使用。

代碼演示:java代碼:

@RequestMapping("/thwith")
    public String thwith(Model model){
        model.addAttribute("today", new Date());
        return "/course/thwith";
    }複製代碼

模版頁面:

<p th:with="df='dd/MMM/yyyy HH:mm'">
          Today is: <span th:text="${#dates.format(today,df)}">13 February 2011</span>
    </p>複製代碼

結果頁面:

<span>02/六月/2019 06:52</span>複製代碼

---java代碼:

@RequestMapping("/thwith")
    public String thwith(Model model){
        List<User> users = new ArrayList<User>();
        users.add(new User("ljk",18));
        users.add(new User("ljk2",18));
        model.addAttribute("users",users);
        return "/course/thwith";
    }複製代碼

模版頁面:

<div th:with="firstEle=${users[0]}">
    <p>
        第一個用戶的名稱是: <span th:text="${firstEle.name}"></span>.
    </p>
</div>複製代碼

結果頁面:

<div>
          <p>
            第一個用戶的名稱是: <span>ljk</span>.
          </p>
</div>複製代碼

還有一種用法是在模版佈局中帶參數的引用片斷中使用方式以下:

<div th:replace="::frag" th:with="onevar=${value1},twovar=${value2}">複製代碼

具體演示請參考模版佈局中的介紹。

Elvis運算符

Elvis運算能夠理解成簡單的判斷是否爲null的三元運算的簡寫,若是值爲nullzhe顯示默認值,若是不爲null 則顯示原有的值。

代碼演示:java代碼:

@RequestMapping("/elvis")
    public String elvis(Model model){
        model.addAttribute("age", null);
        return "/course/elvis";
    }複製代碼

模版頁面:

<p>Age: <span th:text="${age}?: '年齡爲nll'"></span></p>複製代碼

結果頁面:

<p>Age: <span>年齡爲nll</span></p>複製代碼

---java代碼:

@RequestMapping("/elvis")
public String elvis(Model model){
  model.addAttribute("age2", 18);
  return "/course/elvis";
}複製代碼

模版頁面:

<p>Age2: <span th:text="${age2}?: '年齡爲nll'"></span></p>複製代碼

結果頁面:

<p>Age2: <span>18</span></p>複製代碼

三元表達式

咱們能夠在thymeleaf 的語法中使用三元表達式 具體使用方法是在th:x 中經過 表達式?1選項:2選項。

代碼演示:java代碼:

@RequestMapping("/threeElementOperation")
    public String threeElementOperation(Model model){
        return "/course/threeElementOperation";
    }複製代碼

模版頁面:

<p th:class=" 'even'? 'even' : 'odd'" th:text=" 'even'? 'even' : 'odd'"></p>複製代碼

結果頁面:

<p class="even">even</p>複製代碼

---java代碼:

@RequestMapping("/threeElementOperation")
    public String threeElementOperation(Model model){
        model.addAttribute("name", "ljk");
        return "/course/threeElementOperation";
    }複製代碼

模版頁面:

<p th:value="${name eq 'ljk' ? '帥哥':'醜男'}" th:text="${name eq 'ljk' ? '帥哥':'醜男'}"></p>複製代碼

結果頁面:

<p value="帥哥">帥哥</p>複製代碼

條件表達式操做字符:

gt:great than(大於)

ge:great equal(大於等於)

eq:equal(等於)

lt:less than(小於)

le:less equal(小於等於)

ne:not equal(不等於)

No-Operation(_)什麼都不作

Elvis運算符 的一種特殊簡寫操做,當顯示的值爲null 是就什麼都不作。

代碼演示:java代碼:

@RequestMapping("/noOperation")
public String noOperation(Model model){
    model.addAttribute("name", null);
    return "/course/noOperation";
}複製代碼

模版頁面:

<span th:text="${name} ?: _">no user authenticated</span>複製代碼

結果頁面:

<span>no user authenticated</span>複製代碼

標準方言中存在如下固定值布爾屬性:

th:async
th:autofocus
th:autoplay
th:checked
th:controls
th:declare
th:default
th:defer
th:disabled
th:formnovalidate
th:hidden
th:ismap
th:loop
th:multiple
th:novalidate
th:nowrap
th:open
th:pubdate
th:readonly
th:required
th:reversed
th:scoped
th:seamless
th:selected

針對特定的HTML5屬性:

th:abbr
th:accept
th:accept-charset
th:accesskey
th:action
th:align
th:alt
th:archive
th:audio
th:autocomplete
th:axis
th:background
th:bgcolor
th:border
th:cellpadding
th:cellspacing
th:challenge
th:charset
th:cite
th:class
th:classid
th:codebase
th:codetype
th:cols
th:colspan
th:compact
th:content
th:contenteditable
th:contextmenu
th:data
th:datetime
th:dir
th:draggable
th:dropzone
th:enctype
th:for
th:form
th:formaction
th:formenctype
th:formmethod
th:formtarget
th:fragment
th:frame
th:frameborder
th:headers
th:height
th:high
th:href
th:hreflang
th:hspace
th:http-equiv
th:icon
th:id
th:inline
th:keytype
th:kind
th:label
th:lang
th:list
th:longdesc
th:low
th:manifest
th:marginheight
th:marginwidth
th:max
th:maxlength
th:media
th:method
th:min
th:name
th:onabort
th:onafterprint
th:onbeforeprint
th:onbeforeunload
th:onblur
th:oncanplay
th:oncanplaythrough
th:onchange
th:onclick
th:oncontextmenu
th:ondblclick
th:ondrag
th:ondragend
th:ondragenter
th:ondragleave
th:ondragover
th:ondragstart
th:ondrop
th:ondurationchange
th:onemptied
th:onended
th:onerror
th:onfocus
th:onformchange
th:onforminput
th:onhashchange
th:oninput
th:oninvalid
th:onkeydown
th:onkeypress
th:onkeyup
th:onload
th:onloadeddata
th:onloadedmetadata
th:onloadstart
th:onmessage
th:onmousedown
th:onmousemove
th:onmouseout
th:onmouseover
th:onmouseup
th:onmousewheel
th:onoffline
th:ononline
th:onpause
th:onplay
th:onplaying
th:onpopstate
th:onprogress
th:onratechange
th:onreadystatechange
th:onredo
th:onreset
th:onresize
th:onscroll
th:onseeked
th:onseeking
th:onselect
th:onshow
th:onstalled
th:onstorage
th:onsubmit
th:onsuspend
th:ontimeupdate
th:onundo
th:onunload
th:onvolumechange
th:onwaiting
th:optimum
th:pattern
th:placeholder
th:poster
th:preload
th:radiogroup
th:rel
th:rev
th:rows
th:rowspan
th:rules
th:sandbox
th:scheme
th:scope
th:scrolling
th:size
th:sizes
th:span
th:spellcheck
th:src
th:srclang
th:standby
th:start
th:step
th:style
th:summary
th:tabindex
th:target
th:title
th:type
th:usemap
th:value
th:valuetype
th:vspace
th:width
th:wrap
th:xmlbase
th:xmllang
th:xmlspace

內聯

如何使用內連操做

咱們能夠經過 在父標籤聲明 th:inline="text" 來開啓內聯操做。固然若是想整個頁面使用能夠直接聲明在body上便可。具體使用方式以下面代碼所示。

模版頁面:

<div th:inline="text">
<p>Hello, [[${user.name}]]!</p>
</div>複製代碼

結果內容以下:

<div>
<p>Hello,zhuoqianmingyue!</p>
</div>複製代碼

這樣的操做和使用th:text是等同的。

<div>
<p th:text="Hello,+${user.name}"></p>
</div>複製代碼

[[...]]對應於th:text[(...)]對應於th:utext

禁用內聯操做

這咱們能夠經過在父標籤或者本標籤上聲明th:inline="none"來禁用內聯的操做,以下面代碼所示:模版頁面:

<p th:inline="none">A double array looks like this: [[1, 2, 3], [4, 5]]!</p>複製代碼

結果頁面:

<p>A double array looks like this: [[1, 2, 3], [4, 5]]!</p>複製代碼

JavaScript內聯

若是咱們想在JavaScript 中使用內聯操做,須要在 script 標籤上聲明 th:inline="javascript" 而後咱們就能夠 script 標籤中使用內聯操做了。具體使用方式以下面代碼所示:模版頁面:

<script th:inline="javascript">
    var username = [[${user.name}]];
</script>複製代碼

結果頁面:

<script th:inline="javascript">
    var username = "zhuoqianmingyue";
</script>複製代碼

CSS內聯

咱們能夠經過在 style 標籤上聲明 th:inline="css" 來開啓在css中使用內聯的操做,具體操做方式以下:

<style th:inline="css">
  ...
</style>複製代碼

例如,假設咱們將兩個變量設置爲兩個不一樣的String值:classname = 'main elems'align = 'center'咱們能夠像如下同樣使用它們:

<style th:inline="css">
    .[[${classname}]] {
      text-align: [[${align}]];
    }
</style>複製代碼

結果頁面:

<style th:inline="css">
    .main\ elems {
      text-align: center;
    }
</style>複製代碼

模板佈局

定義引用片斷代碼

SpringBoot2.0 使用模版模版佈局須要先引入 thymeleaf的 thymeleaf-layout-dialect依賴

<dependency>
    <groupId>nz.net.ultraq.thymeleaf</groupId>
    <artifactId>thymeleaf-layout-dialect</artifactId>
</dependency>複製代碼

定義footer.html頁面 該頁面就是咱們的引用片斷代碼

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <div th:fragment="copy">
        © 2011 The Good Thymes Virtual Grocery
    </div>
</body>
</html>複製代碼

咱們能夠經過 th:fragment 來定義引用片斷,而後能夠在其餘頁面進行引用。

定義引用頁面 index.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

    <div th:insert="~{footer :: copy}"></div>
</body>
</html>複製代碼

經過 th:insert 和 ~{...}片斷引用表達式 進行引入footer.html中定義的片斷

定義訪問index頁面的 controller

@Controller
@RequestMapping("/layout")
public class LayOutController {
    @RequestMapping("/index")
    public String index(){
        return "/layout/index";
    }
}複製代碼

進行測試http://localhost:8090/sbe/layout/index在這裏插入圖片描述結果頁面:

<div>
  <div>
      © 2011 The Good Thymes Virtual Grocery
  </div>
</div>複製代碼

以下面的代碼2種方式的寫法是一致的。若是你以爲~{footer :: copy}寫法比較麻煩能夠採用簡寫的方式footer :: copy。

<div th:insert="footer :: copy"></div>
<div th:insert="~{footer :: copy}"></div>複製代碼

經過id屬性來聲明片斷

咱們能夠經過 th:fragment 來定義引用片斷,可是咱們也能夠經過在引用片斷代碼上聲明id屬性的方式進行片斷的引用,具體操做方式以下:

定義引用片斷代碼模版頁面 footer.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div id="copy-section" >
    © 2011 The Good Thymes Virtual Grocery
</div>
</body>
</html>複製代碼

引用引用片斷的模版頁面:index.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div th:insert="~{footer :: #copy-section}"></div>
</body>
</html>複製代碼

結果頁面:

<div>
<div id="copy-section">
    © 2011 The Good Thymes Virtual Grocery
</div>
</div>複製代碼

footer :: #copy-section和~{footer :: #copy-section} 結果是一致的。

th:insert和th:replace(和th:include)之間的區別

  • th:insert 是最簡單的:他會將使用th:insert的標籤引用片斷的內容都顯示出來
  • th:replace 插入引用片斷的標籤和內容
  • th:include相似於th:insert,只插入此片斷的內容

th:insertjava代碼:

@Controller
@RequestMapping("/layout")
public class LayoutController {
    @RequestMapping("/index2")
    public String index2(Model model) {
        return "/layout/index2";
    }
}複製代碼

聲明引用片斷模版頁面:footer2.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<footer th:fragment="copy">
  © 2011 The Good Thymes Virtual Grocery
</footer>
</body>
</html>複製代碼

引用片斷模版頁面:index2.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<div th:insert="footer2 :: copy"></div>
<div th:replace="footer2 :: copy"></div>
<div th:include="footer2:: copy"></div>
</body>
</html>複製代碼

---th:insert 結果:

<div>
<footer>
  © 2011 The Good Thymes Virtual Grocery
</footer>
</div>複製代碼

---th:replace結果:

<footer>
  © 2011 The Good Thymes Virtual Grocery
</footer>複製代碼

---th:include結果:

<div>
  © 2011 The Good Thymes Virtual Grocery
</div>複製代碼

帶參數的引用片斷

定義引用片斷代碼模版頁面 footer.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<div th:fragment="frag (onevar,twovar)">
    <p th:text="${onevar} + ' - ' + ${twovar}">...</p>
</div>
</body>
</html>複製代碼

引用引用片斷的模版頁面:index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
    <div th:insert="footer :: frag('a','b')"></div>
</body>
</html>複製代碼

結果頁面:

<div>
<div>
    <p>a - b</p>
</div>
</div>複製代碼

th:insert="footer ::frag (onevar='a',twovar='b')" 和th:insert="footer :: frag('a','b')效果是相等的。還有另外一種寫法就是使用th:withth:insert="::frag" th:with="onevar='a',twovar='b'"

刪除模版片斷

咱們爲了方便經過直接查看下面的頁面 productList.html (主要是爲了做爲原型頁面進行查看)咱們須要添加一些模擬數據。

<table>
  <tr>
    <th>NAME</th>
    <th>PRICE</th>
    <th>IN STOCK</th>
    <th>COMMENTS</th>
  </tr>
  <tr th:each="prod : ${prods}" th:class="${prodStat.odd}? 'odd'">
    <td th:text="${prod.name}">Onions</td>
    <td th:text="${prod.price}">2.41</td>
    <td th:text="${prod.inStock}? #{true} : #{false}">yes</td>
    <td>
      <span th:text="${#lists.size(prod.comments)}">2</span> comment/s
      <a href="comments.html" 
         th:href="@{/product/comments(prodId=${prod.id})}" 
         th:unless="${#lists.isEmpty(prod.comments)}">view</a>
    </td>
  </tr>
  <tr class="odd">
    <td>Blue Lettuce</td>
    <td>9.55</td>
    <td>no</td>
    <td>
      <span>0</span> comment/s
    </td>
  </tr>
  <tr>
    <td>Mild Cinnamon</td>
    <td>1.99</td>
    <td>yes</td>
    <td>
      <span>3</span> comment/s
      <a href="comments.html">view</a>
    </td>
  </tr>
</table>複製代碼

在上面的代碼中模擬數據的代碼,可是咱們經過正常的controller訪問該頁面的時候會顯示出下面的模擬數據。

<tr class="odd">
    <td>Blue Lettuce</td>
    <td>9.55</td>
    <td>no</td>
    <td>
      <span>0</span> comment/s
    </td>
  </tr>
  <tr>
    <td>Mild Cinnamon</td>
    <td>1.99</td>
    <td>yes</td>
    <td>
      <span>3</span> comment/s
      <a href="comments.html">view</a>
    </td>
  </tr>複製代碼

咱們直接查看該頁面的效果以下:在這裏插入圖片描述

經過url訪問查看該頁面的效果:在這裏插入圖片描述

thymeleaf 爲咱們提供了 th:remove 幫助咱們解決這個問題:

<tr class="odd" th:remove="all">
    <td>Blue Lettuce</td>
    <td>9.55</td>
    <td>no</td>
    <td>
      <span>0</span> comment/s
    </td>
  </tr>
  <tr th:remove="all">
    <td>Mild Cinnamon</td>
    <td>1.99</td>
    <td>yes</td>
    <td>
      <span>3</span> comment/s
      <a href="comments.html">view</a>
    </td>
  </tr>
  複製代碼

咱們在模擬數據上聲明th:remove="all" 後在此經過url訪問 沒有了咱們以前的模擬數據在這裏插入圖片描述

直接查看該頁面仍是能夠查看到咱們的模擬數據的。在這裏插入圖片描述

all屬性中的這個值是什麼意思?th:remove能夠根據其價值以五種不一樣的方式表現:

  • all:刪除包含標記及其全部子標記。
  • body:不要刪除包含標記,但刪除其全部子標記。
  • tag:刪除包含標記,但不刪除其子項。
  • all-but-first:刪除除第一個以外的全部包含標記的子項。
  • none: 沒作什麼。此值對於動態評估頗有用。

當咱們知道沒有屬性的含義後咱們能夠經過在 聲明一次便可,無需在經過定義多個 th:remove="all"

預約義的工具對象

dates

處理日期數據 生成,轉換,獲取日期的具體天數 年數。

代碼演示:

java代碼:

@RequestMapping("/dates")
    public String dates(Model model) throws ParseException{
        Date date = new Date();
        model.addAttribute("date",date);
        
        String dateStr = "2018-05-30";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date2 =  sdf.parse(dateStr); 
        Date[] datesArray = new Date[2];
        datesArray[0] = date;
        datesArray[1] = date2;
        model.addAttribute("datesArray",datesArray);
        
        List<Date> datesList = new ArrayList<Date>();
        datesList.add(date);
        datesList.add(date2);
        model.addAttribute("datesList",datesList);
        return "/course/dates";
    }複製代碼

format操做

java代碼:

Date date = new Date();複製代碼

模版頁面:

<span th:text="${#dates.format(date)}">4564546</span>複製代碼

結果頁面:

<span>2019年5月30日 上午10時03分24秒 </span>複製代碼

---java代碼:

Date date = new Date();複製代碼

模版頁面:

<span th:text="${#dates.format(date, 'dd/MMM/yyyy HH:mm')}">4564546</span>複製代碼

結果頁面:

<span>30/五月/2019 10:03 </span>複製代碼

---java代碼:

Date[] datesArray = new Date[2];
        datesArray[0] = date;
        datesArray[1] = date2;複製代碼

模版頁面:

<p th:text="${#dates.format(datesArray, 'yyyy-MM-dd HH:mm')}"></p>複製代碼

結果頁面:

<p>2019-05-30 10:03</p>複製代碼

不知爲什麼這裏只是取出了一個日期數據

---java代碼:

List<Date> datesList = new ArrayList<Date>();
        datesList.add(date);
        datesList.add(date2);
        model.addAttribute("datesList",datesList);複製代碼

模版頁面:

<p th:text="${#dates.listFormat(datesList, 'dd/MMM/yyyy HH:mm')}"></p>複製代碼

結果頁面:

<p>[30/五月/2019 10:03, 30/五月/2018 00:00]</p>複製代碼

獲取日期屬性操做java代碼:

Date date = new Date();複製代碼

模版頁面:

<p th:text="${#dates.day(date)} "></p>複製代碼

結果頁面:

<p>30</p>複製代碼

---java代碼:

Date date = new Date();複製代碼

模版頁面:

<p th:text="${#dates.month(date)}"></p>複製代碼

結果頁面:

<p>5</p>複製代碼

---java代碼:

Date date = new Date();複製代碼

模版頁面:

<p th:text="${#dates.monthName(date)}"></p>複製代碼

結果頁面:

<p>五月</p>複製代碼

---java代碼:

Date date = new Date();複製代碼

模版頁面:

<p th:text="${#dates.monthNameShort(date)} "></p>     複製代碼

結果頁面:

<p>五月</p>複製代碼

---java代碼:

Date date = new Date();複製代碼

模版頁面:

<p th:text="${#dates.year(date)}"></p>複製代碼

結果頁面:

<p>2019</p>複製代碼

---java代碼:

Date date = new Date();複製代碼

模版頁面:

<p th:text="${#dates.dayOfWeek(date)}"></p>      複製代碼

結果頁面:

<p>5</p>複製代碼

---java代碼:

Date date = new Date();複製代碼

模版頁面:

<p th:text="${#dates.dayOfWeekName(date)}"></p> 複製代碼

結果頁面:

<p>星期四</p>複製代碼

---java代碼:

Date date = new Date();複製代碼

模版頁面:

<p th:text="${#dates.dayOfWeekNameShort(date)}"></p>複製代碼

結果頁面:

<p>星期四</p>複製代碼

---java代碼:

Date date = new Date();複製代碼

模版頁面:

<p th:text="${#dates.hour(date)}"></p>複製代碼

結果頁面:

<p>10</p>複製代碼

---java代碼:

Date date = new Date();複製代碼

模版頁面:

<p th:text="${#dates.minute(date)}"></p>複製代碼

結果頁面:

<p>10</p>複製代碼

---java代碼:

Date date = new Date();複製代碼

模版頁面:

<p th:text="${#dates.second(date)}"></p>複製代碼

結果頁面:

<p>45</p>複製代碼

---java代碼:

Date date = new Date();複製代碼

模版頁面:

<p th:text="${#dates.millisecond(date)} "></p>複製代碼

結果頁面:

<p>853</p>複製代碼

生成日期操做

模版頁面:

<p th:text="${#dates.createNow()}"></p>複製代碼

結果頁面:

<p>Thu May 30 10:15:55 CST 2019</p>複製代碼

---模版頁面:

<p th:text="${#dates.format(#dates.createNow())}"></p>複製代碼

結果頁面:

<p>2019年5月30日 上午10時15分55秒</p>複製代碼

---模版頁面:

<p th:text="${#dates.create('2019','05','30')}"></p>複製代碼

結果頁面:

<p>Thu May 30 00:00:00 CST 2019</p>複製代碼

---模版頁面:

<p th:text="${#dates.create('2019','05','31','10','18')}"></p>複製代碼

結果頁面:

<p>Fri May 31 10:18:00 CST 2019</p>複製代碼

---模版頁面:

<p th:text="${#dates.create('2019','05','30','10','18','34')}"></p>複製代碼

結果頁面:

<p>Thu May 30 10:18:34 CST 2019</p>複製代碼

---模版頁面:

<p th:text="${#dates.createToday()}"></p>複製代碼

結果頁面:

<p>Thu May 30 00:00:00 CST 2019</p>複製代碼
numbers

處理數字數據的轉換。包括:

  • 對不夠位數的數字進行補0(formatInteger )
  • 設置千位分隔符(formatInteger)
  • 精確小數點(formatDecimal )
  • 設置百分號(formatPercent )
  • 生成數組(sequence )

代碼演示:

@RequestMapping("/numbers")
    public String numbers(Model model) throws ParseException{
        return "/course/numbers";
    }複製代碼

數字進行補0操做

模板代碼:

<p th:text="${#numbers.formatInteger('123',4)}"></p>複製代碼

結果頁面:

<p>0123</p>複製代碼

---模板代碼:

<p th:text="${#numbers.formatInteger('123',3)}"></p>複製代碼

結果頁面:

<p>123</p>複製代碼

---模板代碼:

<p th:text="${#numbers.formatInteger('123',2)}"></p>複製代碼

結果頁面:

<p>123</p>複製代碼

---Java代碼

@RequestMapping("/numbers")
    public String numbers(Model model) throws ParseException{
        List<Integer> numList = new ArrayList<Integer>();
        numList.add(1);
        numList.add(12);
        numList.add(13);
        model.addAttribute("numList",numList);
        return "/course/numbers";
  }複製代碼

模板代碼:

<p th:text="${#numbers.listFormatInteger(numList,3)}"></p>複製代碼

結果頁面:

<p>[001, 012, 013]</p>複製代碼

千位分隔符操做模板代碼:

<p th:text="${#numbers.formatInteger('1000',2,'POINT')}"></p>複製代碼

結果頁面:

<p>1.000</p>複製代碼

---模板代碼:

<p th:text="${#numbers.formatInteger('1000',6,'POINT')}"></p>複製代碼

結果頁面:

<p>001.000</p>複製代碼

---模板代碼:

<p th:text="${#numbers.formatInteger('1000',7,'POINT')}"></p>複製代碼

結果頁面:

<p>0.001.000</p>複製代碼

---模板代碼:

<p th:text="${#numbers.formatInteger('1000',2,'COMMA')}"></p>複製代碼

結果頁面:

<p>1,000</p>複製代碼

---模板代碼:

<p th:text="${#numbers.formatInteger('1000',2,'WHITESPACE')}"></p>複製代碼

結果頁面:

<p>1 000</p>複製代碼

---模板代碼:

<p th:text="${#numbers.formatInteger('1000',2,'NONE')}"></p>複製代碼

結果頁面:

<p>1000</p>複製代碼

---模板代碼:

<p th:text="${#numbers.formatInteger('1000',2,'DEFAULT')}"></p>複製代碼

結果頁面:

<p>1,000</p>複製代碼

精確小數點操做模板代碼:

<p th:text="${#numbers.formatDecimal('10.123',3,2)}"></p>複製代碼

結果頁面:

<p>010.12</p>複製代碼

---模板代碼:

<p th:text="${#numbers.formatDecimal('1000.123',5,'POINT',2,'COMMA')}"></p>複製代碼

結果頁面:

<p>01.000,12</p>複製代碼

錢顯示符號操做

模板代碼:

<p th:text="${#numbers.formatCurrency('1000')}"></p>複製代碼

結果頁面:

<p>¥1,000.00</p>複製代碼

百分比操做模板代碼:

<p th:text="${#numbers.formatPercent('0.2',2, 4)}"></p>複製代碼

結果頁面:

<p>20.0000%</p>複製代碼

---模板代碼:

<p th:text="${#numbers.formatPercent('0.2',3, 2)}"></p>複製代碼

結果頁面:

<p>020.00%</p>複製代碼

生成數組操做

模板代碼:

<div th:each="num : ${#numbers.sequence(0,4)}" >
          <p th:text="${num}"></p>
</div>複製代碼

結果頁面:

<div><p>0</p></div>
<div><p>1</p></div> 
<div><p>2</p></div>
<div><p>3</p></div>
<div><p>4</p></div>複製代碼

---模板代碼:

<div th:each="num : ${#numbers.sequence(0,4,1)}" >
         <p th:text="${num}"></p>
</div>複製代碼

結果頁面:

<div><p>0</p></div>
<div><p>1</p></div> 
<div><p>2</p></div>
<div><p>3</p></div>
<div><p>4</p></div>複製代碼

---模板代碼:

<div th:each="num : ${#numbers.sequence(0,10,2)}" >
         <p th:text="${num}"></p>
</div>複製代碼

結果頁面:

<div><p>0</p></div>
<div><p>2</p></div>
<div><p>4</p></div>複製代碼
strings

處理String的相關操做,包括:

  • 字符串轉換(toString)
  • 檢查字符串是否爲空(isEmpty)
  • 字符串是爲空替換操做(defaultString)
  • 檢查字符串中是否包含某個字符串(contains containsIgnoreCase)
  • 檢查字符串是以片斷開頭仍是結尾(startsWith endsWith)
  • 截取(substring substringAfter)
  • 替換(replace)
  • 追加(prepend append)
  • 變動大小寫(toUpperCase toLowerCase)
  • 拆分和組合字符串(arrayJoin arraySplit)
  • 去空格(trim)
  • 縮寫文本(abbreviate)
  • 字符串鏈接(concat)

代碼演示:java 代碼

@RequestMapping("/strings")
    public String strings(Model model){
        Object object = "123";
        model.addAttribute("object",object);
        
        List<Integer> numList = new ArrayList<Integer>();
        numList.add(1);
        numList.add(12);
        numList.add(13);
        model.addAttribute("numList",numList);
}複製代碼

Java代碼

Object object = "123";複製代碼

模板代碼:

<p th:text="${object}"></p>複製代碼

結果頁面:

<p>123</p>複製代碼

toString操做

Java代碼

Object object = "123";複製代碼

模板代碼:

<p th:text="${#strings.toString(object)}"></p>複製代碼

結果頁面:

<p>123</p>複製代碼

---Java代碼

List<Integer> numList = new ArrayList<Integer>();
    numList.add(1);
    numList.add(12);
    numList.add(13);複製代碼

模板代碼:

<p th:text="${#strings.toString(numList)}"></p>複製代碼

結果頁面:

<p>[1, 12, 13]</p>複製代碼

isEmpty操做Java代碼

String name = null;複製代碼

模板代碼:

<p th:text="${#strings.isEmpty(name)}"></p>複製代碼

結果頁面:

<p>true</p>複製代碼

---Java代碼

List<String> nameList = new ArrayList<String>();
        nameList.add("1");
        nameList.add(null);複製代碼

模板代碼:

<p th:text="${#strings.listIsEmpty(nameList)}"></p>複製代碼

結果頁面:

<p>[false, true]</p>複製代碼

---Java代碼

Set<String> nameSet = new HashSet<String>();
        nameSet.add(null);
        nameSet.add("1");複製代碼

模板代碼:

<p th:text="${#strings.setIsEmpty(nameSet)}"></p>複製代碼

結果頁面:

<p>[true, false]</p>複製代碼

defaultString操做Java代碼

String name = null;複製代碼

模板代碼:

<p th:text="${#strings.defaultString(text,'該值爲null')}"></p>複製代碼

結果頁面:

<p>該值爲null</p>複製代碼

---Java代碼

List<String> nameList = new ArrayList<String>();
        nameList.add("1");
        nameList.add(null);複製代碼

模板代碼:

<p th:text="${#strings.listDefaultString(textList,'該值爲null')}"></p>複製代碼

結果頁面:

<p>[abc, 該值爲null]</p>複製代碼

contains操做模板代碼:

<p th:text="${#strings.contains('abcez','ez')}"></p>複製代碼

結果頁面:

<p>true</p>複製代碼

---模板代碼:

<p th:text="${#strings.containsIgnoreCase('abcEZ','ez')}"></p>複製代碼

結果頁面:

<p>true</p>複製代碼

startsWith endsWith 操做

模板代碼:

<p th:text="${#strings.startsWith('Donabcez','Don')}"></p>複製代碼

結果頁面:

<p>true</p>複製代碼

---模板代碼:

<p th:text="${#strings.endsWith('Donabcezn','n')}"></p> 複製代碼

結果頁面:

<p>true</p>複製代碼

indexOf操做模板代碼:

<p th:text="${#strings.indexOf('abcefg','e')}"></p> 複製代碼

結果頁面:

<p>3</p>複製代碼

substring操做模板代碼:

<p th:text="${#strings.substring('abcefg',3,5)}"></p>   複製代碼

結果頁面:

<p>ef</p>複製代碼

replace操做模板代碼:

<p th:text="${#strings.replace('lasabce','las','ler')}"></p>複製代碼

結果頁面:

<p>lerabce</p>複製代碼

prepend操做模板代碼:

<p th:text="${#strings.prepend('abc','012')}"></p>複製代碼

結果頁面:

<p>012abc</p>複製代碼

append操做模板代碼:

<p th:text="${#strings.append('abc','456')}"></p>複製代碼

結果頁面:

<p>abc456</p>複製代碼

toUpperCase操做模板代碼:

<p th:text="${#strings.toUpperCase('abc')}"></p>複製代碼

結果頁面:

<p>ABC</p>複製代碼

toLowerCase操做模板代碼:

<p th:text="${#strings.toLowerCase('ABC')}"></p>  複製代碼

結果頁面:

<p>abc</p>複製代碼

length操做模板代碼:

<p th:text="${#strings.length('abc')}"></p>複製代碼

結果頁面:

<p>3</p>複製代碼

trim操做模板代碼:

<p th:text="${#strings.trim(' abc ')}"></p>複製代碼

結果頁面:

<p>abc</p>複製代碼

abbreviate操做模板代碼:

<p th:text="${#strings.abbreviate('12345678910',10)}"></p>複製代碼

結果頁面:

<p>1234567...</p>複製代碼

#objects

處理Object對象的操做 包含obj不爲空返回改值若是爲空返回默認值(nullSafe)java代碼

@RequestMapping("/objects")
public String objects(Model model){
  Object obj = null;
  model.addAttribute("obj",obj);
}複製代碼

模板代碼:

<p th:text="${#objects.nullSafe(obj,'該對象爲null')}"></p>複製代碼

結果頁面:

<p>該對象爲null</p>複製代碼
bools

判斷對象是否爲ture或者是否爲false的操做。

  • 數字 1 爲 ture , 0 爲 false;
  • "on" 爲 true, "off" 爲false;
  • "true" 爲true, "false"爲 false;

isTrue操做模板代碼:

<p th:text="${#bools.isTrue(true)} "></p>複製代碼

結果頁面:

<p>true</p>複製代碼

---模板代碼:

<p th:text="${#bools.isTrue(false)} "></p>複製代碼

結果頁面:

<p>false</p>複製代碼

---模板代碼:

<p th:text="${#bools.isTrue('on')} "></p>複製代碼

結果頁面:

<p>true</p>複製代碼

---模板代碼:

<p th:text="${#bools.isTrue('off')} "></p>複製代碼

結果頁面:

<p>false</p>複製代碼

---模板代碼:

<p th:text="${#bools.isTrue('true')} "></p>複製代碼

結果頁面:

<p>true</p>複製代碼

---模板代碼:

<p th:text="${#bools.isTrue('false')} "></p>複製代碼

結果頁面:

<p>false</p>複製代碼

模板代碼:

<p th:text="${#bools.isTrue(1)} "></p>複製代碼

結果頁面:

<p>true</p>複製代碼

---模板代碼:

<p th:text="${#bools.isTrue(0)} "></p>複製代碼

結果頁面:

<p>false</p>複製代碼
arrays

處理數組的相關操做的內置對象,包含:

  • 轉換數組 toStringArray toIntegerArray,
  • 獲取數組的長度(length ),
  • 判斷數組是否爲空(isEmpty )
  • 是否包含某個元素(contains)
  • 是否包含一批元素(containsAll)

    其中 toStringArray 等操做接受的是Object對象,containsAll 接受一批元素支持數組和集合的參數。

toStringArray操做java代碼

@RequestMapping("/arrays")
public String arrays(Model model){
  List<String> object = new ArrayList<String>();
  object.add("1");
  object.add("2");
  model.addAttribute("object",object);
}複製代碼

模板代碼:

<p th:text="${#arrays.toStringArray(object)} "></p>複製代碼

結果頁面:

<p>[Ljava.lang.String;@3cca655d</p>複製代碼

length操做java代碼

Integer[] array = {1,2,3};複製代碼

模板代碼:

<p th:text="${#arrays.length(array)} "></p>複製代碼

結果頁面:

<p>3</p>複製代碼

isEmpty操做java代碼

Integer[] array = {1,2,3};複製代碼

模板代碼:

<p th:text="${#arrays.isEmpty(array)} "></p>複製代碼

結果頁面:

<p>false</p>複製代碼

contains操做java代碼

Integer[] array = {1,2,3};複製代碼

模板代碼:

<p th:text="${#arrays.contains(array,1)} "></p>複製代碼

結果頁面:

<p>true</p>複製代碼

containsAll操做java代碼

Integer[] array = {1,2,3};
Integer[] array2 = {1,3};複製代碼

模板代碼:

<p th:text="${#arrays.containsAll(array,array2)} "></p>複製代碼

結果頁面:

<p>true</p>複製代碼
lists

處理 list 相關操做的內置對象,包括:

  • 計算長度(size)
  • 檢查list是否爲空(isEmpty)
  • 檢查元素是否包含在list中(contains,containsAll)
  • 對給定list的副本排序(sort)

java代碼

@RequestMapping("/lists")
public String lists(Model model){
   List<Integer> list = new ArrayList<Integer>();
   list.add(1);
   list.add(3);
   list.add(2);
   model.addAttribute("list",list);
 }複製代碼

模板代碼:

<p th:text="${#lists.size(list)} "></p>複製代碼

結果頁面:

<p>3</p>複製代碼

---java代碼:

List<Integer> list = new ArrayList<Integer>();
 list.add(1);
 list.add(3);
 list.add(2);複製代碼

模板代碼:

<p th:text="${#lists.isEmpty(list)} "></p>複製代碼

結果頁面:

<p>false</p>
複製代碼

---java代碼:

List<Integer> list = new ArrayList<Integer>();
 list.add(1);
 list.add(3);
 list.add(2);複製代碼

模板代碼:

<p th:text="${#lists.contains(list, 1)}"></p>複製代碼

結果頁面:

<p>true</p>複製代碼

---java代碼:

List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(3);
list.add(2);
List<Integer> list2 = new ArrayList<Integer>();
list2.add(1);
list2.add(2);複製代碼

模板代碼:

<!-- elements 能夠是數組 集合 list -->
<p th:text="${#lists.containsAll(list,list2)}"></p>複製代碼

結果頁面:

<p>true</p>複製代碼

---java代碼:

List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(3);
list.add(2);複製代碼

模板代碼:

<p th:text="${#lists.sort(list)}"></p>複製代碼

結果頁面:

<p>[1, 2, 3]</p>複製代碼
sets

處理 set 相關操做的內置對象,包括:

  • 轉換爲Set(toSet)
  • 計算長度(size)
  • 檢查set是否爲空(isEmpty)
  • 檢查元素是否包含在set中 (contains,containsAll)

size操做

java代碼

@RequestMapping("/sets")
public String sets(Model model){
   Set<Integer> set = new HashSet<Integer>();
   set.add(1);
   set.add(2);
   set.add(3);
   set.add(4);
   model.addAttribute("set",set);
 }複製代碼

模板代碼:

<p th:text="${#sets.size(set)} "></p>複製代碼

結果頁面:

<p>3</p>
複製代碼

isEmpty 操做

java代碼:

Set<Integer> set = new HashSet<Integer>();
  set.add(1);
  set.add(2);
  set.add(3);
  set.add(4);複製代碼

模板代碼:

<p th:text="${#sets.isEmpty(set)} "></p>複製代碼

結果頁面:

<p>false</p>
複製代碼

contains操做

java代碼:

Set<Integer> set = new HashSet<Integer>();
  set.add(1);
  set.add(2);
  set.add(3);
  set.add(4);複製代碼

模板代碼:

<p th:text="${#sets.contains(set, 1)}"></p>複製代碼

結果頁面:

<p>true</p>
複製代碼

containsAll操做

java代碼

Set<Integer> set = new HashSet<Integer>();
  set.add(1);
  set.add(2);
  set.add(3);
  set.add(4);
  
Integer[] elements = {1,2};
model.addAttribute("elements",elements);複製代碼

模板代碼:

<p th:text="${#sets.containsAll(set, elements)}"></p>複製代碼

結果頁面:

<p>true</p>

複製代碼

sort操做

java代碼:

Set<Integer> set = new HashSet<Integer>();
  set.add(1);
  set.add(2);
  set.add(3);
  set.add(4);複製代碼

模板代碼:

<p th:text="${#lists.sort(list)}"></p>複製代碼

結果頁面:

<p>[1, 2, 3]</p>
複製代碼

maps

處理 map相關操做的內置對象,包括:

  • 計算長度(size)
  • 檢查map是否爲空(isEmpty)
  • 檢查映射中是否包含鍵或值(containsKey,containsAllKeys,containsValue)

java代碼:

@RequestMapping("/maps")
public String maps(Model model){
   Map<String,Integer> map = new HashMap<String,Integer>();
   map.put("1",1);
   map.put("2",2);
   map.put("3",3);
   model.addAttribute("map",map);
}複製代碼

模板代碼:

<p th:text="${#maps.size(map)} "></p>複製代碼

結果頁面:

<p>3</p>複製代碼

---java代碼:

Map<String,Integer> map = new HashMap<String,Integer>();
   map.put("1",1);
   map.put("2",2);
   map.put("3",3);複製代碼

模板代碼:

<p th:text="${#maps.isEmpty(map)} "></p>複製代碼

結果頁面:

<p>false</p>複製代碼

java代碼:

Map<String,Integer> map = new HashMap<String,Integer>();
   map.put("1",1);
   map.put("2",2);
   map.put("3",3);複製代碼

模板代碼:

<p th:text="${#maps.containsKey(map, '1')}"></p>複製代碼

結果頁面:

<p>true</p>複製代碼

java代碼:

Map<String,Integer> map = new HashMap<String,Integer>();
   map.put("1",1);
   map.put("2",2);
   map.put("3",3);
String[] keys = {"1","2"};
model.addAttribute("keys",keys);複製代碼

模板代碼:

<!-- keys 能夠是數組能夠是集合 -->
<p th:text="${#maps.containsAllKeys(map, keys)}"></p>複製代碼

結果頁面:

<p>true</p>複製代碼

---java代碼:

Map<String,Integer> map = new HashMap<String,Integer>();
   map.put("1",1);
   map.put("2",2);
   map.put("3",3);複製代碼

模板代碼:

<p th:text="${#maps.containsValue(map, 2)}"></p>複製代碼

結果頁面:

<p>true</p>複製代碼

java代碼:

Map<String,Integer> map = new HashMap<String,Integer>();
   map.put("1",1);
   map.put("2",2);
   map.put("3",3);
Integer[] values = {1,2};
model.addAttribute("values",values);複製代碼

模板代碼:

<!-- values 能夠是數組能夠是集合 -->
<p th:text="${#maps.containsAllValues(map, values)}"></p>複製代碼

結果頁面:

<p>true</p>複製代碼
aggregates

用戶處理集合或者數組的一些統計操做,包括:

  • 求和(sum)
  • 求平均值(avg)
  • 處理包裝類型或基本類型的數組或集合

求和操做

java代碼:

@RequestMapping("/aggregates")
public String aggregates(Model model){
   Integer[] array = {1,2,3,4};
   model.addAttribute("array",array);
   return "/course/aggregates";
}複製代碼

模板代碼:

<p th:text="${#aggregates.sum(array)} "></p>複製代碼

結果頁面:

<p>10</p>複製代碼

java代碼:

List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(2);
list.add(3);
list.add(4);複製代碼

模板代碼:

<p th:text="${#aggregates.sum(list)} "></p>複製代碼

結果頁面:

<p>10</p>複製代碼

求平均值操做

java代碼:

Integer[] array = {1,2,3,4};複製代碼

模板代碼:

<p th:text="${#aggregates.avg(array)} "></p>複製代碼

結果頁面:

<p>2.5</p>複製代碼

---

java代碼:

List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(2);
list.add(3);
list.add(4);複製代碼

模板代碼:

<p th:text="${#aggregates.avg(list)} "></p>複製代碼

結果頁面:

<p>2.5</p>複製代碼

小結

本文主要介紹 Thymeleaf 的基礎用法、內聯、模板佈局、預約義的工具對象。總體來看Thymeleaf 使用語法仍是很強大的,可是我這裏不會強烈安利你使用 Thymeleaf,正如 Thymeleaf 官方所說:「不管如何,比較技術的最好方法是本身使用它們,並感受哪一個最適合你!」 你一樣能夠選擇使用 Velocity 或 FreeMarker。

代碼示例

具體代碼示例請查看個人GitHub 倉庫 springbootexamples 中的 spring-boot-2.x-thymeleaf 下的 course 包下查看。

GitHub:https://github.com/zhuoqianmingyue/springbootexamples

參考文獻:

https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html

https://blog.csdn.net/liubin5620/article/details/80470619

相關文章
相關標籤/搜索