1. 程式人生 > >Spring Boot2(五):使用Spring Boot結合Thymeleaf模板引擎使用總結

Spring Boot2(五):使用Spring Boot結合Thymeleaf模板引擎使用總結

一、Thymeleaf概述

一般來說,常用的模板引擎有JSP、Velocity、Freemarker、Thymeleaf 。

SpringBoot推薦的 Thymeleaf – 語法更簡單,功能更強大;

Thymeleaf是一種Java XML/XHTML/HTML5模板引擎,可以在Web和非Web環境中使用。
它更適合在基於MVC的Web應用程式的檢視層提供XHTML/HTML5,但即使在離線環境中,它也可以處理任何XML檔案。它提供了完整的Spring Framework整合。

二、 標準表示式語法

它們分為四類:

  • 1.變量表達式
  • 2.選擇或星號表示式
  • 3.文字國際化表示式
  • 4.URL 表示式

變量表達式

變量表達式即 OGNL 表示式或 Spring EL 表示式(在 Spring 術語中也叫 model attributes)。如下所示:
${session.user.name}

它們將以HTML標籤的一個屬性來表示:

<span th:text="${book.author.name}">  
<li th:each="book : ${books}">  

選擇(星號)表示式

選擇表示式很像變量表達式,不過它們用一個預先選擇的物件來代替上下文變數容器(map)來執行,如下:
*{customer.name}

被指定的 object 由 th:object 屬性定義:

<div th:object="${book}">  
  ...  
  <span th:text="*{title}">...</span>  
  ...  
</div>  

文字國際化表示式

文字國際化表示式允許我們從一個外部檔案獲取區域文字資訊(.properties),用 Key 索引 Value,還可以提供一組引數(可選).

#{main.title}  
#{message.entrycreated(${entryId})}  

可以在模板檔案中找到這樣的表示式程式碼:

<table>  
  ...  
  <th th:text="#{header.address.city}">...</th>  
  <th th:text="#{header.address.country}">...</th>  
  ...  
</table>  

URL 表示式

URL 表示式指的是把一個有用的上下文或回話資訊新增到 URL,這個過程經常被叫做 URL 重寫。
@{/order/list}

URL還可以設定引數:
@{/order/details(id=${orderId})}

相對路徑:
@{../documents/report}

讓我們看這些表示式:

<form th:action="@{/createOrder}">  
<a href="main.html" th:href="@{/main}">

變量表達式和星號表達有什麼區別嗎?

如果不考慮上下文的情況下,兩者沒有區別;星號語法評估在選定物件上表達,而不是整個上下文
什麼是選定物件?就是父標籤的值,如下:

<div th:object="${session.user}">
  <p>Name: <span th:text="*{firstName}">Sebastian</span>.</p>
  <p>Surname: <span th:text="*{lastName}">Pepper</span>.</p>
  <p>Nationality: <span th:text="*{nationality}">Saturn</span>.</p>
</div>

這是完全等價於:

<div th:object="${session.user}">
  <p>Name: <span th:text="${session.user.firstName}">Sebastian</span>.</p>
  <p>Surname: <span th:text="${session.user.lastName}">Pepper</span>.</p>
  <p>Nationality: <span th:text="${session.user.nationality}">Saturn</span>.</p>
</div>

當然,美元符號和星號語法可以混合使用:

  <div th:object="${session.user}">
      <p>Name: <span th:text="*{firstName}">Sebastian</span>.</p>
      <p>Surname: <span th:text="${session.user.lastName}">Pepper</span>.</p>
      <p>Nationality: <span th:text="*{nationality}">Saturn</span>.</p>
  </div>

表示式支援的語法

字面(Literals)

  • 文字文字(Text literals): 'one text', 'Another one!',…
  • 數字文字(Number literals): 0, 34, 3.0, 12.3,…
  • 布林文字(Boolean literals):true, false
  • 空(Null literal):null
  • 文字標記(Literal tokens):one, sometext, main,…

文字操作(Text operations)

  • 字串連線(String concatenation):+
  • 文字替換(Literal substitutions):|The name is ${name}|

算術運算(Arithmetic operations)

  • 二元運算子(Binary operators):+, -, *, /, %
  • 減號(單目運算子)Minus sign (unary operator):-

布林操作(Boolean operations)

  • 二元運算子(Binary operators):and, or
  • 布林否定(一元運算子)Boolean negation (unary operator):!, not

比較和等價(Comparisons and equality)

  • 比較(Comparators):>, <, >=, <= (gt, lt, ge, le)
  • 等值運算子(Equality operators):==, != (eq, ne)

條件運算子(Conditional operators)

  • If-then:(if) ? (then)
  • If-then-else:(if) ? (then) : (else)
  • Default: (value) ?:(defaultvalue)

所有這些特徵可以被組合並巢狀:

'User is of type ' + (${user.isAdmin()} ? 'Administrator' : (${user.type} ?: 'Unknown'))

三、常用的th標籤

官方文件詳細的一批:
https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html

關鍵字 功能介紹 案例
th:id 替換id <input th:id="'xxx' + ${collect.id}"/>
th:text 文字替換 <p th:text="${collect.description}">description</p>
th:utext 支援html的文字替換 <p th:utext="${htmlcontent}">conten</p>
th:object 替換物件 <div th:object="${session.user}">
th:value 屬性賦值 <input th:value="${user.name}" />
th:with 變數賦值運算 <div th:with="isEven=${prodStat.count}%2==0"></div>
th:style 設定樣式 th:style="'display:' + @{(${sitrue} ? 'none' : 'inline-block')} + ''"
th:onclick 點選事件 th:onclick="'getCollect()'"
th:each 屬性賦值 tr th:each="user,userStat:${users}">
th:if 判斷條件 <a th:if="${userId == collect.userId}" >
th:unless 和th:if判斷相反 <a th:href="@{/login}" th:unless=${session.user != null}>Login</a>
th:href 連結地址 <a th:href="@{/login}" th:unless=${session.user != null}>Login</a> />
th:switch 多路選擇 配合th:case 使用 <div th:switch="${user.role}">
th:case th:switch的一個分支 <p th:case="'admin'">User is an administrator</p>
th:fragment 佈局標籤,定義一個程式碼片段,方便其它地方引用 <div th:fragment="alert">
th:include 佈局標籤,替換內容到引入的檔案 <head th:include="layout :: htmlhead" th:with="title='xx'"></head> />
th:replace 佈局標籤,替換整個標籤到引入的檔案 <div th:replace="fragments/header :: title"></div>
th:selected selected選擇框 選中 th:selected="(${xxx.id} == ${configObj.dd})"
th:src 圖片類地址引入 <img class="img-responsive" alt="App Logo" th:src="@{/img/logo.png}" />
th:inline 定義js指令碼可以使用變數 <script type="text/javascript" th:inline="javascript">
th:action 表單提交的地址 <form action="subscribe.html" th:action="@{/subscribe}">
th:remove 刪除某個屬性 <tr th:remove="all"> 1.all:刪除包含標籤和所有的孩子。2.body:不包含標記刪除,但刪除其所有的孩子。3.tag:包含標記的刪除,但不刪除它的孩子。4.all-but-first:刪除所有包含標籤的孩子,除了第一個。5.none:什麼也不做。這個值是有用的動態評估。
th:attr 設定標籤屬性,多個屬性可以用逗號分隔 比如th:attr="src=@{/image/aa.jpg},title=#{logo}",此標籤不太優雅,一般用的比較少。

還有非常多的標籤,這裡只列出最常用的幾個,由於一個標籤內可以包含多個th:x屬性,其生效的優先順序順序為:include,each,if/unless/switch/case,with,attr/attrprepend/attrappend,value/href,src ,etc,text/utext,fragment,remove。

四、表示式

簡單表示式

  • 變量表達式:${…}
  • 選擇變量表達式:*{…}
  • 訊息表示式:#{…}
  • 連結表示式:@{…}
  • 片段表達:~{…}

資料的型別

  • 文字:’one text’, ‘Another one!’,…
  • 數字文字:0, 34, 3.0, 12.3,…
  • 布林文字:true, false
  • NULL文字:null
  • 文字標記:one, sometext, main,…

文字操作

  • 字串拼接:+
  • 字面替換:|The name is ${name}|

算術運算

  • 二進位制運算子:+, -, *, /, %
  • 減號(一元運算子):-

布林運算

  • 二進位制運算子:and, or
  • 布林否定(一元運算子):!, false

條件運算子

  • 比較值:>, <, >=, <=
  • 相等判斷: ==, !=

條件判斷

  • (if) ? (then)
  • (if) ? (then) : (else)
  • 三元:(value) ? value : defaultvalue

五、表示式物件

表示式裡面的物件可以幫助我們處理要展示的內容,比如表示式的工具類dates可以格式化時間,這些內建類的熟練使用,可以讓我們使用Thymeleaf的效率提高很多。

  • #ctx: 操作當前上下文.
  • #vars: 操作上下文變數.
  • #request: (僅適用於Web專案) HttpServletRequest物件.
  • #response: (僅適用於Web專案) HttpServletResponse 物件.
  • #session: (僅適用於Web專案) HttpSession 物件.
  • #servletContext: (僅適用於Web專案) ServletContext 物件.

表示式實用工具類:

  • #execInfo: 操作模板的工具類,包含了一些模板資訊,比如:${ #execInfo.templateName }
  • #uris: url處理的工具
  • #conversions: methods for executing the configured conversion service (if any).
  • #dates: 方法來源於 java.util.Date 物件,用於處理時間,比如:格式化.
  • #calendars: 類似於 #dates, 但是來自於 java.util.Calendar 物件.
  • #numbers: 用於格式化數字.
  • #strings: methods for String objects: contains, startsWith, prepending/appending, etc.
  • #objects: 普通的object物件方法.
  • #bools: 判斷bool型別的工具.
  • #arrays: 陣列操作工具.
  • #lists: 列表操作資料.
  • #sets: Set操作工具.
  • #maps: Map操作工具.
  • #aggregates: 運算元組或集合的工具.

六、幾種常用的使用方法

1、賦值、字串拼接

<p  th:text="${collect.description}">description</p>
<span th:text="'Welcome to our application, ' + ${user.name} + '!'">

字串拼接還有另外一種簡潔的寫法

<span th:text="|Welcome to our application, ${user.name}!|">

2、條件判斷 If/Unless

Thymeleaf中使用th:if和th:unless屬性進行條件判斷,下面的例子中,<a>標籤只有在th:if中條件成立時才顯示:

<a th:if="${myself=='yes'}" > </i> </a>
<a th:unless=${session.user != null} th:href="@{/login}" >Login</a>

th:unlessth:if 恰好相反,只有表示式中的條件不成立,才會顯示其內容。

也可以使用 (if) ? (then) : (else)這種語法來判斷顯示的內容

3、for 迴圈

<tr  th:each="collect,iterStat : ${collects}"> 
   <th scope="row" th:text="${collect.id}">1</th>
   <td >
      <img th:src="${collect.webLogo}"/>
   </td>
   <td th:text="${collect.url}">Mark</td>
   <td th:text="${collect.title}">Otto</td>
   <td th:text="${collect.description}">@mdo</td>
   <td th:text="${terStat.index}">index</td>
</tr>

iterStat稱作狀態變數,屬性有:

  • index:當前迭代物件的 index(從0開始計算)
  • count: 當前迭代物件的 index(從1開始計算)
  • size:被迭代物件的大小
  • current:當前迭代變數
  • even/odd:布林值,當前迴圈是否是偶數/奇數(從0開始計算)
  • first:布林值,當前迴圈是否是第一個
  • last:布林值,當前迴圈是否是最後一個

4、URL

URL 在 Web 應用模板中佔據著十分重要的地位,需要特別注意的是 Thymeleaf 對於 URL 的處理是通過語法 @{...}來處理的。 如果需要 Thymeleaf 對 URL 進行渲染,那麼務必使用 th:hrefth:src 等屬性,下面是一個例子

<!-- Will produce 'http://localhost:8080/standard/unread' (plus rewriting) -->
 <a  th:href="@{/standard/{type}(type=${type})}">view</a>

<!-- Will produce '/gtvg/order/3/details' (plus rewriting) -->
<a href="details.html" th:href="@{/order/{orderId}/details(orderId=${o.id})}">view</a>

設定背景

<div th:style="'background:url(' + @{/<path-to-image>} + ');'"></div>

根據屬性值改變背景

 <div class="media-object resource-card-image"  th:style="'background:url(' + @{(${collect.webLogo}=='' ? 'img/favicon.png' : ${collect.webLogo})} + ')'" ></div>

幾點說明:

  • 上例中 URL 最後的(orderId=${o.id})表示將括號內的內容作為 URL 引數處理,該語法避免使用字串拼接,大大提高了可讀性
  • @{...}表示式中可以通過{orderId}訪問 Context 中的 orderId 變數
  • @{/order}是 Context 相關的相對路徑,在渲染時會自動新增上當前 Web 應用的 Context 名字,假設 context 名字為 app,那麼結果應該是 /app/order

5、內聯 js

內聯文字:[[…]] 內聯文字的表示方式,使用時,必須先用th:inline="text/javascript/none"啟用,th:inline可以在父級標籤內使用,甚至作為 body 的標籤。內聯文字儘管比th:text的程式碼少,不利於原型顯示。

<script th:inline="javascript">
/*<![CDATA[*/
...
var username = /*[[${sesion.user.name}]]*/ 'Sebastian';
var size = /*[[${size}]]*/ 0;
...
/*]]>*/
</script>

js 附加程式碼:

/*[+
var msg = 'This is a working application';
+]*/

js 移除程式碼:

/*[- */
var msg = 'This is a non-working template';
/* -]*/

6、內嵌變數

為了模板更加易用,Thymeleaf 還提供了一系列 Utility 物件(內置於 Context 中),可以通過 # 直接訪問:

  • dates : java.util.Date的功能方法類。
  • calendars : 類似#dates,面向java.util.Calendar
  • numbers : 格式化數字的功能方法類
  • strings : 字串物件的功能類,contains,startWiths,prepending/appending等等。
  • objects: 對objects的功能類操作。
  • bools: 對布林值求值的功能方法。
  • arrays:對陣列的功能類方法。
  • lists: 對lists功能類方法
  • sets
  • maps

下面用一段程式碼來舉例一些常用的方法:

dates

/*
 * Format date with the specified pattern
 * Also works with arrays, lists or sets
 */
${#dates.format(date, 'dd/MMM/yyyy HH:mm')}
${#dates.arrayFormat(datesArray, 'dd/MMM/yyyy HH:mm')}
${#dates.listFormat(datesList, 'dd/MMM/yyyy HH:mm')}
${#dates.setFormat(datesSet, 'dd/MMM/yyyy HH:mm')}

/*
 * Create a date (java.util.Date) object for the current date and time
 */
${#dates.createNow()}

/*
 * Create a date (java.util.Date) object for the current date (time set to 00:00)
 */
${#dates.createToday()}

strings

/*
 * Check whether a String is empty (or null). Performs a trim() operation before check
 * Also works with arrays, lists or sets
 */
${#strings.isEmpty(name)}
${#strings.arrayIsEmpty(nameArr)}
${#strings.listIsEmpty(nameList)}
${#strings.setIsEmpty(nameSet)}

/*
 * Check whether a String starts or ends with a fragment
 * Also works with arrays, lists or sets
 */
${#strings.startsWith(name,'Don')}                  // also array*, list* and set*
${#strings.endsWith(name,endingFragment)}           // also array*, list* and set*

/*
 * Compute length
 * Also works with arrays, lists or sets
 */
${#strings.length(str)}

/*
 * Null-safe comparison and concatenation
 */
${#strings.equals(str)}
${#strings.equalsIgnoreCase(str)}
${#strings.concat(str)}
${#strings.concatReplaceNulls(str)}

/*
 * Random
 */
${#strings.randomAlphanumeric(count)}

七、使用基本步驟

我認為可以大致分為四步:

  1. pom.xml 新增 Thymeleaf 模板引擎。
  2. application.yml 配置 Thymeleaf 資訊。
  3. 建立controller類,編寫程式碼。
  4. 建立模板,編寫html程式碼。

1. pom.xml 新增依賴

<dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

2. .properties 配置 Thymeleaf 資訊

server:
  port: 8081
spring:
  thymeleaf:
    # 是否啟用
    enabled: true
    # 模板編碼
    encoding: UTF-8
    # 模板模式
    mode: HTML5
    # 模板存放路徑
    prefix: classpath:/templates/
    # 模板字尾
    suffix: .html
    # 啟用快取,建議生產開啟
    cache: false
    # 校驗模板是否存在
    check-template-location: true
    # Content-type值
    servlet:
      content-type: text/html
  # 加配置靜態資源
  resources:
    static-locations: classpath:/

3. 建立controller類,編寫程式碼

@RequestMapping("/me")
public String kownMe(Map<String,Object> map) {
    List<String> list = new ArrayList<String>();
    list.add("鳥不拉屎:一個正在努力Coding的未來架構師");
    list.add("記錄菜鳥的成長");
    list.add("個人部落格:https://niaobulashi.com");
    list.add("github部落格:https://niaobulashi.github.io");
    map.put("msg", "Yoyoyoyoyo");
    map.put("images", "Yoyoyoyoyo");
    map.put("lists", list);
    return "me";
}

注意:返回的”me″是我HTML檔案 me.html的名稱哦

4. 建立 page1.html 。編寫html程式碼

只要把寫好的HTML頁面放在 classpath:/templates/ 下,thymeleaf就能自動渲染。

注意匯入:

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

否則沒提示哦~

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org" >
<head>
    <meta charset="UTF-8">
    <meta content="text/html;charset=UTF-8"/>
    <title>鳥不拉屎</title>
    <link rel="stylesheet" href="static/layui/css/layui.css">
</head>
<body>
<div class="layui-container">
    <h1>templates示例</h1>
    <!-- th:text="" 將h2的文字值視為指定引數 -->
    <hr>
    <h2 th:text="${msg}">這是h2</h2>
    <fieldset class="layui-elem-field layui-field-title" style="margin-top: 20px;">
        <legend>迴圈</legend>
    </fieldset>
    <table style="text-align: center" class="layui-table" lay-skin="line"  >
        <colgroup>
            <col width="350">
        </colgroup>
        <thead>
        <tr>
            <th>NAME</th>
        </tr>
        </thead>
        <tbody>
        <!-- th迴圈遍歷傳來的引數 -->
        <tr th:each="str : ${lists}" >
            <th th:text="${str}" ></th>
        </tr>
        </tbody>
    </table>
    <img th:src="${images}" >
</div>
</body>
</html>

執行效果(樣式用的layUI~~):

八、參考

Thymeleaf 使用詳解

SpringBoot中的Thymeleaf 模板引擎

Thymeleaf官方文