1. 程式人生 > 程式設計 >史上最詳 Thymeleaf 使用教程

史上最詳 Thymeleaf 使用教程

前言

操作前建議先參考我的另一篇部落格:玩轉 SpringBoot 2 快速整合 | Thymeleaf 篇 檢視如何在SpringBoot 中使用 Thymeleaf。還有一點需要注意的是:模版頁面中的 html 上需要宣告 Thymeleaf 的名稱空間,具體程式碼如下:

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

接下來就可以開始 Thymeleaf 使用教程了!

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

基礎語法

文字標籤 th:text/th:utext

用於文字內容的顯示操作。

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

程式碼演示:

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

th:text 進行文字替換 不會解析html

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

結果頁面:

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

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

th:utext 進行文字替換 會解析html

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

遊覽器展示效果如下圖:在這裡插入圖片描述使用 + 和 | | 效果是一樣的,如下程式碼所示:

<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,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','31','10','18')}"></p>複製程式碼

結果頁面:

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

---模版頁面:

<p th:text="${#dates.create('2019','30','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','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','COMMA')}"></p>複製程式碼

結果頁面:

<p>1,000</p>複製程式碼

---模板程式碼:

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

結果頁面:

<p>1 000</p>複製程式碼

---模板程式碼:

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

結果頁面:

<p>1000</p>複製程式碼

---模板程式碼:

<p th:text="${#numbers.formatInteger('1000','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','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',4)}"></p>複製程式碼

結果頁面:

<p>20.0000%</p>複製程式碼

---模板程式碼:

<p th:text="${#numbers.formatPercent('0.2',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',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,3};複製程式碼

模板程式碼:

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

結果頁面:

<p>3</p>複製程式碼

isEmpty操作java程式碼

Integer[] array = {1,3};複製程式碼

模板程式碼:

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

結果頁面:

<p>false</p>複製程式碼

contains操作java程式碼

Integer[] array = {1,3};複製程式碼

模板程式碼:

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

結果頁面:

<p>true</p>複製程式碼

containsAll操作java程式碼

Integer[] array = {1,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,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,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,3);複製程式碼

模板程式碼:

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

結果頁面:

<p>false</p>複製程式碼

java程式碼:

   Map<String,3);複製程式碼

模板程式碼:

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

結果頁面:

<p>true</p>複製程式碼

java程式碼:

Map<String,3);
String[] keys = {"1","2"};
model.addAttribute("keys",keys);複製程式碼

模板程式碼:

<!-- keys 可以是陣列可以是集合 -->
<p th:text="${#maps.containsAllKeys(map,keys)}"></p>複製程式碼

結果頁面:

<p>true</p>複製程式碼

---java程式碼:

Map<String,3);複製程式碼

模板程式碼:

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

結果頁面:

<p>true</p>複製程式碼

java程式碼:

Map<String,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,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,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