第 2-4 課:模板引擎 Thymeleaf 高階用法

上一課我們介紹了 Thymeleaf 最常用的使用語法,這一課我們繼續學習 Thymeleaf 高階的使用方式,並對這些使用方式進行總結分類。其實上一課的內容,基本可以滿足 Thymeleaf 80% 的使用場景,高階用法會在某些場景下提供更高效、便捷的使用方式。

內聯 [ [ ] ]

如果不想通過 th 標籤而是簡單地訪問 model 對象數據,或是想在 javascript 代碼塊裏訪問 model 中的數據,則要使用內聯的方法。

內聯文本:[ [...] ] 內聯文本的表示方式,使用時,必須先用在 th:inline="text/javascript/none" 激活,th:inline 可以在父級標籤內使用,甚至可以作爲 body 的標籤。內聯文本比 th:text 的代碼少,不利於原型顯示。

頁面 inline.html(文本內聯):

<div>
    <h1>內聯</h1>
    <div th:inline="text" >
        <p>Hello, [[${userName}]] !</p>
        <br/>
    </div>
</div>

以上代碼等價於:

<div>
    <h1>不使用內聯</h1>
    <p th:text="'Hello, ' + ${userName} + ' !'"></p>
    <br/>
</div>

通過以上代碼可以看出使用內聯語法會更簡潔一些。

如果想在腳本中使用後端傳遞的值,則必須使用腳本內聯,腳本內聯可以在 js 中取到後臺傳過來的參數:

<script th:inline="javascript">
    var name = [[${userName}]] + ', Sebastian';
    alert(name);
</script>

這段腳本的含義是在訪問頁面的時候,根據後端傳值拼接 name 值,並以 alert 的方式彈框展示。

後端傳值:

@RequestMapping("/inline")
public String inline(ModelMap map) {
    map.addAttribute("userName", "neo");
    return "inline";
}

啓動項目後在瀏覽器中輸入該網址:http://localhost:8080/inline,則會出現下面的結果:

頁面會先跳出一個 alert 提示框,然後再展示使用內聯和不使用內聯的頁面內容。

基本對象

Thymeleaf 包含了一些基本對象,可以用於我們的視圖中,這些基本對象使用 # 開頭。

  • #ctx:上下文對象
  • #vars:上下文變量
  • #locale:區域對象
  • #request:(僅 Web 環境可用)HttpServletRequest 對象
  • #response:(僅 Web 環境可用)HttpServletResponse 對象
  • #session:(僅 Web 環境可用)HttpSession 對象
  • #servletContext:(僅 Web 環境可用)ServletContext 對象

Thymeleaf 在 Web 環境中,有一系列的快捷方式用於訪問請求參數、會話屬性等應用屬性,以其中幾個常用的對象作爲示例來演示。

  • #request:直接訪問與當前請求關聯的 javax.servlet.http.HttpServletRequest 對象;
  • #session:直接訪問與當前請求關聯的 javax.servlet.http.HttpSession 對象。

後臺添加方法傳值:

@RequestMapping("/object")
public String object(HttpServletRequest request) {
    request.setAttribute("request","i am request");
    request.getSession().setAttribute("session","i am session");
    return "object";
}

使用 request 和 session 分別傳遞了一個值,再來查看頁面 object.html。

<body>
    <div >
        <h1>基本對象</h1>
        <p th:text="${#request.getAttribute('request')}">
        <br/>
        <p th:text="${session.session}"></p>
         Established locale country: <span th:text="${#locale.country}">CN</span>.
    </div>
</body>

啓動項目後在瀏覽器中輸入該網址:http://localhost:8080/object,則會出現下面的結果:

基本對象

i am request

i am session

Established locale country: CN.

第一個展示了 request 如何使用參數,第二行展示了 session 的使用,session 直接使用 . 即可獲取到 session 中的值,最後展示了 locale 的用法。

內嵌變量

爲了模板更加易用,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:set 的實用方法
  • maps:map 的實用方法

下面用一段代碼來舉例說明一些常用的方法,頁面是 utility.html。

1. dates

可以使用 dates 對日期格式化,創建當前時間等操作。

<!--格式化時間-->
<p th:text="${#dates.format(date, 'yyyy-MM-dd HH:mm:ss')}">neo</p>
<!--創建當前時間 精確到天-->
<p th:text="${#dates.createToday()}">neo</p>
<!--創建當前時間 精確到秒-->
<p th:text="${#dates.createNow()}">neo</p>

2. strings

strings 內置了一些對字符串經常使用的函數。

<!--判斷是否爲空-->
<p th:text="${#strings.isEmpty(userName)}">userName</p>
<!--判斷 list 是否爲空-->
<p th:text="${#strings.listIsEmpty(users)}">userName</p>
<!--輸出字符串長度-->
<p th:text="${#strings.length(userName)}">userName</p>
<!--拼接字符串-->
<p th:text="${#strings.concat(userName,userName,userName)}"></p>
<!--創建自定長度的字符串-->
<p th:text="${#strings.randomAlphanumeric(count)}">userName</p>

後端傳值:

@RequestMapping("/utility")
public String utility(ModelMap map) {
    map.addAttribute("userName", "neo");
    map.addAttribute("users", getUserList());
    map.addAttribute("count", 12);
    map.addAttribute("date", new Date());
    return "utility";
}

啓動項目後在瀏覽器中輸入該網址:http://localhost:8080/utility,則會出現下面的結果:

內嵌變量

2018-09-26 20:49:07

Wed Sep 26 00:00:00 CST 2018

Wed Sep 26 20:49:07 CST 2018

false

[false, false, false]

3

neoneoneo

QKERBVPRHFS9

接下來總結一下 Thymeleaf 表達式。

表達式

表達式共分爲以下五類。

  • 變量表達式:${...}
  • 選擇或星號表達式:*{...}
  • 文字國際化表達式:#{...}
  • 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>  

title 即爲 book 的屬性。

文字國際化表達式

文字國際化表達式允許我們從一個外部文件獲取區域文字信息(.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}">

片段表達式

片段表達式是 3.x 版本新增的內容。片段表達式是一種標記的片段,並將其移動到模板中的方法。片段表達式的優勢是,片段可以被複制或者作爲參數傳遞給其他模板等。

最常見的用法是使用 th:insert 或 th:replace: 插入片段:

<div th:insert="~{commons :: main}">...</div>

也可以在頁面的其他位置去使用:

<div th:with="frag=~{footer :: #main/text()}">
  <p th:insert="${frag}">
</div>

片段表達式可以有參數。

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

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

<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 標籤

頁面常用的 HTML 標籤幾乎都有 Thymeleaf 對應的 th 標籤。

關鍵字 功能介紹 案例
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。

Thymeleaf 配置

我們可以通過 application.properties 文件靈活的配置 Thymeleaf 的各項特性,以下爲 Thymeleaf 的配置和默認參數:

# THYMELEAF (ThymeleafAutoConfiguration)
#開啓模板緩存(默認值:true)
spring.thymeleaf.cache=true 
#檢查模板是否存在,然後再呈現
spring.thymeleaf.check-template=true 
#檢查模板位置是否正確(默認值:true)
spring.thymeleaf.check-template-location=true
#Content-Type的值(默認值:text/html)
spring.thymeleaf.content-type=text/html
#開啓MVC Thymeleaf視圖解析(默認值:true)
spring.thymeleaf.enabled=true
#模板編碼
spring.thymeleaf.encoding=UTF-8
#要被排除在解析之外的視圖名稱列表,用逗號分隔
spring.thymeleaf.excluded-view-names=
#要運用於模板之上的模板模式。另見StandardTemplate-ModeHandlers(默認值:HTML5)
spring.thymeleaf.mode=HTML5
#在構建URL時添加到視圖名稱前的前綴(默認值:classpath:/templates/)
spring.thymeleaf.prefix=classpath:/templates/
#在構建URL時添加到視圖名稱後的後綴(默認值:.html)
spring.thymeleaf.suffix=.html
#Thymeleaf 模板解析器在解析器鏈中的順序,默認情況下,它排第一位,順序從1開始,只有在定義了額外的 TemplateResolver Bean 時才需要設置這個屬性。
spring.thymeleaf.template-resolver-order=
#可解析的視圖名稱列表,用逗號分隔
spring.thymeleaf.view-names=

在實際項目中可以根據實際使用情況來修改。

總結

Thymeleaf 的使用方式非常靈活,可以結合 JS 來獲取後端傳遞的值,Thymeleaf 本身也內嵌了很多對象和函數方便我們在頁面來直接調用。Thymeleaf 通過不同的表達式來靈活的控制頁面結構和內容,配合着 Spring Boot 的使用,Thymeleaf 可以通過多項參考來控制其特性。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章