02- Thymeleaf 入門

ThymeLeaf

模板引擎

含義

1、市面上主流的 Java 模板引擎有:JSP、Velocity、Freemarker、Thymeleaf
2、JSP 本質也是模板引擎,Spring Boot 官方推薦使用 “Thymeleaf”模板引擎
3、模板引擎原理圖如下,模板引擎的作用都是將模板(頁面)和數據進行整合然後輸出顯示,區別在於不同的模板使用不同的語法,如 JSP 的JSTL表達式,以及J SP 自己的表達式和語法,同理 Thymeleaf 也有自己的語法

在這裏插入圖片描述

ThymeLeaf入門

官網介紹

Thymeleaf 官網:https://www.thymeleaf.org/

1.Thymeleaf is a modern server-side Java template engine for both web and standalone environments.
Thymeleaf是⾯向Web和獨⽴環境的現代服務器端Java模板引擎,能夠處理HTML,XML,JavaScript,CSS甚⾄純⽂本。

2.Thymeleaf's main goal is to bring elegant natural templates to your development workflow — HTML that can be correctly displayed in browsers and also work as static prototypes, allowing for stronger collaboration in development teams.
Thymeleaf旨在提供⼀個優雅的、⾼度可維護的創建模板的⽅式。 爲了實現這⼀⽬標,Thymeleaf建⽴在⾃然模板的概念上,將其邏輯注⼊到模板⽂件中,不會影響模板設計原型。 這改善了設計的溝通,彌合了設計和開發團隊之間的差距。

3.With modules for Spring Framework, a host of integrations with your favourite tools, and the ability to plug in your own functionality, Thymeleaf is ideal for modern-day HTML5 JVM web development — although there is much more it can do.
對於Spring框架模塊,一個允許你集成你最喜歡的工具的平臺,並且能夠插入自己的功能,Thymeleaf是理想的現代JVM HTML5 web開發工具,雖然它可以做得多。

優勢體會

1.Thymeleaf 在有網絡和無網絡的環境下皆可運行,即它可以讓美工在瀏覽器查看頁面的靜態效果,也可以讓程序員在服務器查看帶數據的動態頁面效果。這是由於它支持 html 原型,然後在 html 標籤裏增加額外的屬性來達到模板+數據的展示方式。瀏覽器解釋 html 時會忽略未定義的標籤屬性,所以 thymeleaf 的模板可以靜態地運行;當有數據返回到頁面時,Thymeleaf 標籤會動態地替換掉靜態內容,使頁面動態顯示。

2.Thymeleaf 開箱即用的特性。它提供標準和spring標準兩種方言,可以直接套用模板實現JSTL、 OGNL表達式效果,避免每天套模板、改jstl、改標籤的困擾。同時開發人員也可以擴展和創建自定義的方言。

3.Thymeleaf 提供spring標準方言和一個與 SpringMVC 完美集成的可選模塊,可以快速的實現表單綁定、屬性編輯器、國際化等功能。

官網示例代碼

<table>
  <thead>
    <tr>
      <th th:text="#{msgs.headers.name}">Name</th>
      <th th:text="#{msgs.headers.price}">Price</th>
    </tr>
  </thead>
  <tbody>
    <tr th:each="prod: ${allProducts}">
      <td th:text="${prod.name}">Oranges</td>
      <td th:text="${#numbers.formatDecimal(prod.price, 1, 2)}">0.99</td>
    </tr>
  </tbody>
</table>

SpringBoot 集成 Thymeleaf

導入依賴

<!-- 引入thymeleaf模板引擎-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

默認規則

默認前綴:DEFAULT_PREFIX = "classpath:/templates/"
默認後綴:DEFAULT_SUFFIX = ".html"
類似於 Spring MVC 的視圖解析器

案例書寫

後臺代碼

@RequestMapping("hello")
public String hello(Model model){
    model.addAttribute("name","張三");
    return "success";
}

前端頁面

<h1 th:text="${name}">hehe</h1>

需要注意的配置文件

# thymeleaf 配置信息
# 前綴最後別忘了添加一個 / (多麼痛的領悟)
spring.thymeleaf.prefix=classpsth:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.servlet.content-type=text/html
spring.thymeleaf.mode=HTML5
# 代碼測試 需要禁用緩存, 生產環境下可以設置爲 true
spring.thymeleaf.cache=false

常用標籤

添加命名空間, 作用是提示信息

<html lang="en" xmlns:th="http://www.thymeleaf.org">

文本

model.addAttribute("a","<b>你好</b>");
model.addAttribute("b","<b>你好</b>");
<a th:text="${a}"></a>  顯示結果爲 <b>你好</b>
將內容完整的顯示出來 標籤也不會 轉義
<a th:utext="${b}"></a> 顯示結果爲 加粗之後的 你好
如果內容中有標籤存在, 則將標籤轉義

日期格式

<h1 th:text="${#dates.format(phone.birthday,'yyyy-MM-dd HH:mm:ss')}"></h1>

簡化對象獲取功能

<tr>
    <td th:text="${phone.name}"></td>
    <td th:text="${phone.gender}"></td>
    <td th:text="${phone.birthday}"></td>
    <td th:text="${phone.address}"></td>
</tr>

簡化爲

<tr th:object="${phone}">
    <td th:text="*{name}"></td>
    <td th:text="*{gender}"></td>
    <td th:text="*{birthday}"></td>
    <td th:text="*{address}"></td>
</tr>

URL 路徑顯示

th:src="@{}"

th:href="@{}"

th:action="@{}"

<script th:src="@{js/test.js}"></script>
<script th:src="@{/js/test.js}"></script>
<script src="/js/test.js"></script>

傳遞參數

<a href="" th:href="@{/demo(name=張三)}">訪問後臺demo</a>
<a href="" th:href="@{/demo(name=張三,age=20)}">訪問後臺demo</a>

加載靜態文件

靜態文件在 SpringBoot中的默認配置

# 默認配置 , 寫不寫都是如此
spring.mvc.static-path-pattern=classpath:/static/**

算術與邏輯運算

Thyme Leaf 標準表達式⽀持算術運算:+, - ,*,/(除),%(取餘)
表達式中的值可以與 >,<,>= ,<= ,==,!= 符號進⾏⽐較。 
⼀個更簡單的替代⽅案是使⽤這些運算符的⽂本別名:
	gt(>),lt(<),ge(>=),le(<=),eq(==),neq(!=)。

邏輯運算符:and(與)、or(或)、!(非),not(非)

條件判斷

<h1 th:if="${age} gt 18">年齡大於18</h1>
<h1 th:if="${age} lt 18">年齡小於18</h1>

表單

th:id
th:name
th:value
th:checked
th:selected

條件分支

if

<p th:if="true">th:if="true"</p>

需要注意的是 :

1)如果表達式結果爲布爾值,則爲 true 或者 false
2)如果表達式的值爲 null,th:if 將判定此表達式爲 false
3)如果值是數字,爲 0 時,判斷爲 false;不爲零時,判定爲 true
4)如果 value 是 String,值爲 “false”、“off”、“no” 時,判定爲 false,否則判斷爲 true,字符串爲空時,也判斷爲 true
5)如果值不是布爾值,數字,字符或字符串的其它對象,只要不爲 null,則判斷爲 true

switch

<!--字符串類型-->
<div th:switch="'For China'">
    <p th:case="'For USA'">美國</p>
    <p th:case="'For UK'">英國</p>
    <p th:case="'For China'">中國</p>
    <p th:case="*">未知國籍</p>
</div>

循環

基本語法

<table  >
    <tr th:each="stu:${list}">
        <td th:text="${stu.name}"></td>
        <td th:text="${stu.age}"></td>
        <td th:text="${stu.address}"></td>
    </tr>

</table>

循環狀態屬性

th:each=“stu,varstatus:${list}”

<table  >
    <tr th:each="stu,varstatus:${list}">
        <td th:text="${varstatus.count}"></td>
        <td th:text="${stu.name}"></td>
        <td th:text="${stu.age}"></td>
        <td th:text="${stu.address}"></td>
    </tr>
</table>

屬性

使⽤ th:each 時,Thymeleaf 提供了⼀種⽤於跟蹤迭代狀態的機制:狀態變量。狀態變量在每個 th:each 屬性中定義,幷包含以下數據:

1)index 屬性:當前迭代索引,從0開始

2)count 屬性:當前的迭代計數,從1開始

3)size 屬性:迭代變量中元素的總量

4)current 屬性:每次迭代的 iter 變量,即當前遍歷到的元素

5)even/odd 布爾屬性:當前的迭代是偶數還是奇數。

6)first 布爾屬性:當前的迭代是否是第⼀個迭代

7)last 布爾屬性:當前的迭代是否是最後⼀個迭代。

<table border="1">
    <thead>
    <tr>
        <th>序號</th>
        <th>工號</th>
        <th>姓名</th>
        <th>生日</th>
        <th>是否已婚</th>
        <th>工資</th>
    </tr>
    </thead>
    <tbody>
    <!-- 遍歷集合,如果被遍歷的變量 userList 爲 null 或者不存在,則不會進行遍歷,也不報錯-->
    <!-- 設置狀態變量 loopStatus,逗號分隔,當爲奇數行時,設置一個 css2 樣式-->
    <tr th:each="user,loopStatus: ${userList}" th:class="${loopStatus.odd}?'css2'">
        <!-- 顯示當前的行序號-->
        <td th:text="${loopStatus.count}"></td>
        <!-- 將用戶的主鍵 uId 存在在 name 屬性中-->
        <td th:text="${user.uId}" th:name="${user.uId}"></td>
        <td th:text="${user.uName}"></td>
        <!-- 使用dates對象格式化日期-->
        <td th:text="${#dates.format(user.birthday, 'yyyy-MM-dd HH:mm')}"></td>
        <!-- 三運運算判斷是否已婚-->
        <td th:text="${user.isMarry}?'是':'否'"></td>
        <td th:text="${user.price}"></td>
    </tr>
    </tbody>
</table>

屬性優先級

​ 當在同⼀個標籤中寫⼊多個 th:* 屬性時會發⽣什麼? 例如:

<ul>
   <li th:each="item : ${items}" th:text="${item.description}">Item description here...</li>
</ul>

期望是 th:each 屬性在 th:text 之前執⾏,以便得到想要的結果,但是 HTML / XML 標準對於標籤屬性的渲染順序沒有任何定義, 因此 Thyme Leaf 如果要達到這種效果,必須在屬性本身中建⽴優先機制,以確保這些屬性按預期⼯作。因此,所有的Thymeleaf 屬性都定義⼀個數字優先級,以便確定在標籤中按順序執⾏。優先級清單如下:

Order(順序) Feature(特徵) Attributes(屬性)
1 Fragment inclusion th:insert 、th:replace
2 Fragment iteration th:each
3 Conditional evaluation th:if 、th:unless、th:switch、 th:case
4 Local variable definition th:object 、th:with
5 General attribute modification th:attr、 th:attrprepend、th:attrappend
6 Specific attribute modification th:value、 th:href、 th:src…
7 Text (tag body modification) th:text 、th:utext
8 Fragment specification th:fragment
9 Fragment removal th:remove

​ 這個優先機制意味着與屬性位置並無關係,只與屬性名有關:

<ul>
   <li th:each="item : ${items}" th:text="${item.description}">Item description here...</li>
</ul>
等價於
<ul>
   <li th:text="${item.description}" th:each="item : ${items}">Item description here...</li>
</ul>

局部變量

​ JSP 中 JSTL 的set 標籤 用於設置變量值和對象屬性

<c:set var="j" value="${1}"/>

​ th:each 迭代中的 變量 其實就是局部變量,僅在 標籤範圍內可⽤,包括所有子元素,可⽤於在該標籤中執⾏優先級低於 th:each 的任何其他 th:* 屬性。

​ Thymeleaf 中可以使用 th:with 進行指定局部變量,局部變量是指定義在模版⽚段中的變量,並且該變量的作⽤域爲所在的模版⽚段。

<div th:with="firstPer=${persons[0]}">
   <p>The name of the first person is <span th:text="${firstPer.name}">Julius Caesar</span>.</p>
</div>
當 th:with 被處理時,firstPer 變量被創建爲局部變量並被添加到來⾃上下⽂ map 中,以便它可以與上下⽂中聲明的任何其他變量⼀起使⽤,但只能在包含的 <div> 標籤內使⽤。

2)可以使用同時定義多個變量,用逗號隔開:

<div th:with="firstPer=${persons[0]},secondPer=${persons[1]}">
   <p>The name of the first person is <span th:text="${firstPer.name}">Julius Caesar</span>.</p>
   <p>But the name of the second person is<span th:text="${secondPer.name}">Marcus Antonius</span>.</p>
</div>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章