史上最詳 Thymeleaf 使用教程

来源:https://www.cnblogs.com/jerry126/archive/2019/09/17/11531310.html
-Advertisement-
Play Games

前言 操作前建議先參考我的另一篇博客: "玩轉 SpringBoot 2 快速整合 | Thymeleaf 篇" 查看如何在SpringBoot 中使用 Thymeleaf。還有一點需要註意的是:模版頁面中的 html 上需要聲明 Thymeleaf 的命名空間,具體代碼如下: 接下來就可以開始 T ...


前言

操作前建議先參考我的另一篇博客:玩轉 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";
    }
}

如果沒有定義 message_en_US.properties 和 message_zh_CN.properties 會預設取message.properties中的信息
如果 Locale = Locale.CHINA 就取 message_zh_CN.properties
如果 Locale = Locale.US 就取 message_en_US.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&amp;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">
        &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" >
    &copy; 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:insert
java代碼:

@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">
  &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:with
th: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

您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 效果 效果圖如下 ​ ​ 實現思路 dom結構 用兩個嵌套的div容器就可以了,父容器來控製圖標顯示的位置,子容器用來寫烏雲的樣式。而陰影和閃電的樣式都用偽元素就可以了,這些都是在css中定義的。 <div class="container"> <div class="stormy"></div> ...
  • 場景 Docker-Compose簡介與Ubuntu Server 上安裝Compose: https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/100902301 在上面實現Compose成功安裝的基礎上,使用Compose啟動項目。 ...
  • Compose簡介 Compose是Docker官方的開源項目,負責對Docker容器集群的快速編排。 Compose是定義和運行多個Docker容器的應用。 舉例來說: 一個項目除了Tomcat容器外,還需要mysql服務容器,Compose允許用戶通過一個單獨的 docker-compose.y ...
  • 什麼是常量 用final修飾的成員變數表示常量,值一旦給定就無法改變! final修飾的變數有三種:靜態變數、實例變數和局部變數,分別表示三種類型的常量。 Class文件中的常量池 在Class文件結構中,最頭的4個位元組用於存儲魔數Magic Number,用於確定一個文件是否能被JVM接受,再接著 ...
  • 引言: 原型模式是什麼?它是在什麼場景下被提出的呢?本章節,我們將詳細瞭解下原型模式。 在軟體系統中,當創建一個類的實例過程過於昂貴或複雜,並且我們需要創建多個這樣類的實例時,如果我們通過new來創建類實例,這就會增加創建類的複雜度和創建過程與客戶代碼複雜的耦合度。如果採用工廠模式來創建這樣的實例對 ...
  • 概述 在開發RESTFull API 和普通的表單提交都需要對用戶提交的數據進行校驗,例如:用戶姓名不能為空,年齡必須大於0 等等。這裡我們主要說的是後臺的校驗,在 SpringBoot 中我們可以通過使用 Hibernate Validator 來進行後臺的數據校驗的。 閑話少說!接下來就開始介紹 ...
  • Devtools 介紹 SpringBoot 提供了熱部署的功能,那啥是熱部署累?SpringBoot官方是這樣說的:只要類路徑上的文件發生更改,就會自動重新啟動應用程式。在IDE中工作時,這可能是一個有用的功能,因為它為代碼更改提供了非常快速的反饋迴圈。預設情況下,將監視類路徑上指向文件夾的任何條 ...
  • 前言 Thymeleaf是一個適用於Web和獨立環境的現代伺服器端Java模板引擎。 Thymeleaf的主要目標是為您的開發工作流程帶來優雅的自然模板 可以在瀏覽器中正確顯示的HTML,也可以用作靜態原型,從而在開發團隊中實現更強大的協作。 通過Spring Framework模塊,與您喜歡的工具 ...
一周排行
    -Advertisement-
    Play Games
  • 前言 本文介紹一款使用 C# 與 WPF 開發的音頻播放器,其界面簡潔大方,操作體驗流暢。該播放器支持多種音頻格式(如 MP4、WMA、OGG、FLAC 等),並具備標記、實時歌詞顯示等功能。 另外,還支持換膚及多語言(中英文)切換。核心音頻處理採用 FFmpeg 組件,獲得了廣泛認可,目前 Git ...
  • OAuth2.0授權驗證-gitee授權碼模式 本文主要介紹如何筆者自己是如何使用gitee提供的OAuth2.0協議完成授權驗證並登錄到自己的系統,完整模式如圖 1、創建應用 打開gitee個人中心->第三方應用->創建應用 創建應用後在我的應用界面,查看已創建應用的Client ID和Clien ...
  • 解決了這個問題:《winForm下,fastReport.net 從.net framework 升級到.net5遇到的錯誤“Operation is not supported on this platform.”》 本文內容轉載自:https://www.fcnsoft.com/Home/Sho ...
  • 國內文章 WPF 從裸 Win 32 的 WM_Pointer 消息獲取觸摸點繪製筆跡 https://www.cnblogs.com/lindexi/p/18390983 本文將告訴大家如何在 WPF 裡面,接收裸 Win 32 的 WM_Pointer 消息,從消息裡面獲取觸摸點信息,使用觸摸點 ...
  • 前言 給大家推薦一個專為新零售快消行業打造了一套高效的進銷存管理系統。 系統不僅具備強大的庫存管理功能,還集成了高性能的輕量級 POS 解決方案,確保頁面載入速度極快,提供良好的用戶體驗。 項目介紹 Dorisoy.POS 是一款基於 .NET 7 和 Angular 4 開發的新零售快消進銷存管理 ...
  • ABP CLI常用的代碼分享 一、確保環境配置正確 安裝.NET CLI: ABP CLI是基於.NET Core或.NET 5/6/7等更高版本構建的,因此首先需要在你的開發環境中安裝.NET CLI。這可以通過訪問Microsoft官網下載並安裝相應版本的.NET SDK來實現。 安裝ABP ...
  • 問題 問題是這樣的:第三方的webapi,需要先調用登陸介面獲取Cookie,訪問其它介面時攜帶Cookie信息。 但使用HttpClient類調用登陸介面,返回的Headers中沒有找到Cookie信息。 分析 首先,使用Postman測試該登陸介面,正常返回Cookie信息,說明是HttpCli ...
  • 國內文章 關於.NET在中國為什麼工資低的分析 https://www.cnblogs.com/thinkingmore/p/18406244 .NET在中國開發者的薪資偏低,主要因市場需求、技術棧選擇和企業文化等因素所致。歷史上,.NET曾因微軟的閉源策略發展受限,儘管後來推出了跨平臺的.NET ...
  • 在WPF開發應用中,動畫不僅可以引起用戶的註意與興趣,而且還使軟體更加便於使用。前面幾篇文章講解了畫筆(Brush),形狀(Shape),幾何圖形(Geometry),變換(Transform)等相關內容,今天繼續講解動畫相關內容和知識點,僅供學習分享使用,如有不足之處,還請指正。 ...
  • 什麼是委托? 委托可以說是把一個方法代入另一個方法執行,相當於指向函數的指針;事件就相當於保存委托的數組; 1.實例化委托的方式: 方式1:通過new創建實例: public delegate void ShowDelegate(); 或者 public delegate string ShowDe ...