SpringBoot2.x 集成 Thymeleaf的詳細(xì)教程
一、Thymeleaf簡(jiǎn)介
Thymeleaf是面向Web和獨(dú)立環(huán)境的現(xiàn)代服務(wù)器Java模板引擎,能夠處理HTML,XML,JavaScript,CSS甚至純文本。
Thymeleaf旨在提供一個(gè)優(yōu)雅的、高度可維護(hù)的創(chuàng)建模板的方式。為了實(shí)現(xiàn)這一目標(biāo),Thymeleaf建立在自然模板的概念上,將其邏輯注入到模板文件中,不會(huì)影響模板設(shè)計(jì)原型。這改善了設(shè)計(jì)的溝通,彌合了設(shè)計(jì)和開發(fā)團(tuán)隊(duì)之間的差距。
Thymeleaf從設(shè)計(jì)之初就遵循Web標(biāo)準(zhǔn)——特別是HTML5標(biāo)準(zhǔn),如果需要,Thymeleaf允許創(chuàng)建完全符合HTML5驗(yàn)證標(biāo)準(zhǔn)的模板。
二、集成Thymeleaf
通過Maven新建一個(gè)名為springboot-thymeleaf
的項(xiàng)目。
1.引入依賴
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- Thymeleaf 起步依賴 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <!-- lombok插件 --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.8</version> </dependency>
2.編寫配置文件
spring: thymeleaf: # 在構(gòu)建URL時(shí)用于查看名稱的前綴,默認(rèn)為classpath:/templates/ prefix: classpath:/templates/ # 在構(gòu)建URL時(shí)附加到視圖名稱的后綴,默認(rèn)為.html suffix: .html # 模板模式,默認(rèn)為HTML mode: HTML # 模板文件編碼,默認(rèn)為UTF-8 encoding: UTF-8 # 是否啟用模板緩存,默認(rèn)為true,表示啟用,false不啟用 cache: false # 在呈現(xiàn)模板之前是否檢查模板存在與否,默認(rèn)為true check-template: true # 是否檢查模板位置存在與否,默認(rèn)為true check-template-location: true
更多的配置可以查看ThymeleafProperties
類:
3.準(zhǔn)備模板
首先按照配置文件中配置的模板前綴在resources
下創(chuàng)建一個(gè)templates
目錄,用于存放模板。然后創(chuàng)建如下名為hello.html
的模板:
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Hello Thymeleaf</title> </head> <body> <div> <span th:text="${hello}">th:text文本替換會(huì)轉(zhuǎn)義html標(biāo)簽,不解析html</span> </div> <hr/> <div> <span th:utext="${hello}">th:utext文本替換不會(huì)轉(zhuǎn)義html標(biāo)簽,會(huì)解析html</span> </div> </body> </html>
<html>
標(biāo)簽中的xmlns:th="http://www.thymeleaf.org
聲明使用Thymeleaf標(biāo)簽。th:text
屬性會(huì)計(jì)算表達(dá)式的值將結(jié)果設(shè)置為標(biāo)簽的標(biāo)簽體。但它會(huì)轉(zhuǎn)義HTML標(biāo)簽,HTML標(biāo)簽會(huì)直接顯示在瀏覽器上。th:utext
屬性不會(huì)轉(zhuǎn)義HTML標(biāo)簽,HTML標(biāo)簽會(huì)被瀏覽器解析。${hello}
是一個(gè)變量表達(dá)式,它包含一個(gè)OGNL(Object-Graph Navigation Language)的表達(dá)式,它會(huì)從上下文中獲取名為hello
的變量,然后在模板上進(jìn)行渲染。
4.Controller層
創(chuàng)建Controller并將模板中要獲取的變量設(shè)置到Model對(duì)象中,如果Controller類上使用的是@Controller
注解,則可以返回跟模板名稱相同的字符串(不包括前綴和后綴),視圖解析器會(huì)解析出視圖具體地址并生成視圖,然后返回給前端控制器進(jìn)行渲染:
package com.rtxtitanv.controller; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; /** * @author rtxtitanv * @version 1.0.0 * @name com.rtxtitanv.controller.ThymeleafController * @description ThymeleafController * @date 2021/7/3 19:23 */ @Controller public class ThymeleafController { @GetMapping("/hello") public String hello(Model model) { model.addAttribute("hello", "<h1>Hello Thymeleaf</h1>"); return "hello"; } }
運(yùn)行項(xiàng)目,瀏覽器訪問http://localhost:8080/hello,發(fā)現(xiàn)數(shù)據(jù)成功渲染到模板:
如果Controller類上使用的是@RestController
注解,則需要將視圖添加到ModelAndView對(duì)象中并返回:
package com.rtxtitanv.controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.servlet.ModelAndView; /** * @author rtxtitanv * @version 1.0.0 * @name com.rtxtitanv.controller.TestController * @description TestController * @date 2021/7/3 19:43 */ @RequestMapping("/test") @RestController public class TestController { @GetMapping("/hello") public ModelAndView hello() { ModelAndView modelAndView = new ModelAndView("hello"); modelAndView.addObject("hello", "<h1>hello thymeleaf</h1>"); return modelAndView; } }
運(yùn)行項(xiàng)目,瀏覽器訪問http://localhost:8080/test/hello,發(fā)現(xiàn)數(shù)據(jù)成功渲染到模板:
三、Thymeleaf常用語(yǔ)法
1.標(biāo)準(zhǔn)表達(dá)式
(1)變量表達(dá)式
${}
表達(dá)式實(shí)際上是在上下⽂中包含的變量的映射上執(zhí)行的OGNL(Object-Graph Navigation Language)對(duì)象。例如:${session.user.name}
。
在Spring MVC啟用的應(yīng)用程序中,OGNL將被替換為SpringEL,但其語(yǔ)法與OGNL相似(實(shí)際上,在大多數(shù)常見情況下完全相同)。
模板variable.html
如下:
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>變量表達(dá)式</title> </head> <body> <p>變量表達(dá)式:${}</p> <div> <p>id: <span th:text="${user.id}"></span></p> <p>username: <span th:text="${user.username}"></span></p> <p>password: <span th:text="${user.password}"></span></p> </div> </body> </html>
User實(shí)體類:
package com.rtxtitanv.model; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; /** * @author rtxtitanv * @version 1.0.0 * @name com.rtxtitanv.model.User * @description User * @date 2021/7/3 19:37 */ @AllArgsConstructor @NoArgsConstructor @Data public class User { private Long id; private String username; private String password; }
ThymeleafController
中新增以下方法:
@GetMapping("/variable") public String variable(Model model) { model.addAttribute("user", new User(1L, "趙云", "qwe123")); return "variable"; }
效果:
在${}
表達(dá)式中還可以使用基本對(duì)象和工具類對(duì)象。這些對(duì)象都以#
開頭?;緦?duì)象:
#ctx
:上下文對(duì)象。#vars
:上下文變量。#locale
:上下文區(qū)域設(shè)置。#request
:(僅在Web Contexts中)HttpServletRequest對(duì)象。#response
:(僅在Web上下⽂中)HttpServletResponse對(duì)象。#session
:(僅在Web上下⽂中)HttpSession對(duì)象。#servletContext
:(僅在Web上下⽂中)ServletContext對(duì)象。
工具類對(duì)象:
#execInfo
:有關(guān)正在處理的模板的信息。#messages
:用于在變量表達(dá)式中獲取外部化消息的方法,與使用#{}語(yǔ)法獲取的方式相同。#uris
:轉(zhuǎn)義URL/URI部分的方法。#conversions
:執(zhí)行配置的轉(zhuǎn)換服務(wù)的方法。#dates
:java.util.Date
對(duì)象的方法。#calendars
:類似于#dates
,但對(duì)應(yīng)java.util.Calendar
對(duì)象。#numbers
:用于格式化數(shù)字對(duì)象的方法。#strings
:字符串對(duì)象的方法。#objects
:一般對(duì)象的方法。#bools
:布爾相關(guān)方法。#arrays
:Array的方法。#lists
:List的方法。#sets
:Set的方法。#maps
:Map的方法。#aggregates
:在數(shù)組或集合上創(chuàng)建聚合的方法。#ids
:處理可能重復(fù)的id屬性的方法。
這些對(duì)象的詳細(xì)方法可以查看官方文檔:https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#appendix-a-expression-basic-objects。
(2)選擇表達(dá)式(星號(hào)語(yǔ)法)
星號(hào)語(yǔ)法*{}
計(jì)算所選對(duì)象而不是整個(gè)上下文的表達(dá)式。也就是說,只要沒有選定的對(duì)象(選定對(duì)象為th:object
屬性的表達(dá)式結(jié)果),$
和*
語(yǔ)法就會(huì)完全相同。
模板asterisk.html
如下:
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>選擇表達(dá)式(星號(hào)語(yǔ)法)</title> </head> <body> <p>*語(yǔ)法</p> <div th:object="${user}"> <p>id: <span th:text="*{id}"></span></p> <p>username: <span th:text="*{username}"></span></p> <p>password: <span th:text="*{password}"></span></p> </div> <p>$語(yǔ)法</p> <div> <p>id: <span th:text="${user.id}"></span></p> <p>username: <span th:text="${user.username}"></span></p> <p>password: <span th:text="${user.password}"></span></p> </div> <p>$和*混合使用</p> <div th:object="${user}"> <p>id: <span th:text="*{id}"></span></p> <p>username: <span th:text="${user.username}"></span></p> <p>password: <span th:text="*{password}"></span></p> </div> <p>對(duì)象選擇到位時(shí)所選對(duì)象將作為#object表達(dá)式變量可⽤于$表達(dá)式</p> <div th:object="${user}"> <p>id: <span th:text="${#object.id}"></span></p> <p>username: <span th:text="${user.username}"></span></p> <p>password: <span th:text="*{password}"></span></p> </div> <p>沒有執(zhí)⾏對(duì)象選擇時(shí)$和*語(yǔ)法等效</p> <div> <p>id: <span th:text="*{user.id}"></span></p> <p>username: <span th:text="*{user.username}"></span></p> <p>password: <span th:text="*{user.password}"></span></p> </div> </body> </html>
ThymeleafController
中新增以下方法:
@GetMapping("/asterisk") public String star(Model model) { model.addAttribute("user", new User(1L, "趙云", "qwe123")); return "asterisk"; }
效果:
(3)URL表達(dá)式
URL表達(dá)式的語(yǔ)法為@{}
。使用th:href
屬性可以對(duì)鏈接進(jìn)行渲染。
模板url.html
如下:
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>URL表達(dá)式</title> </head> <body> <ol> <li><a href="user/one.html" rel="external nofollow" rel="external nofollow" th:href="@{/user/one(id=${user.id})}" rel="external nofollow" >設(shè)置單個(gè)參數(shù)</a></li> <li><a href="user/list.html" rel="external nofollow" th:href="@{/user/list(username=${user.username},password=${user.password})}" rel="external nofollow" >設(shè)置多個(gè)參數(shù)</a></li> <li><a href="user/one.html" rel="external nofollow" rel="external nofollow" th:href="@{/user/one/{id}(id=${user.id})}" rel="external nofollow" >URL路徑中也允許使⽤變量模板(rest風(fēng)格參數(shù))</a></li> <li><a href="user/update.html" rel="external nofollow" th:href="@{${url}(id=${user.id})}" rel="external nofollow" >URL基數(shù)也可以是計(jì)算另⼀個(gè)表達(dá)式的結(jié)果</a></li> <li><a href="store/user/update.html" rel="external nofollow" th:href="@{'/store' + ${url}(id=${user.id})}" rel="external nofollow" >url基數(shù)也可以是計(jì)算另⼀個(gè)表達(dá)式的結(jié)果</a></li> </ol> <hr/> <!-- th:action設(shè)置表單提交地址 --> <form id="login-form" th:action="@{/hello}"> <button>提交</button> </form> </body> </html>
注意:
th:href
屬性會(huì)計(jì)算要使用的URL并將該值設(shè)置為<a>
標(biāo)簽的href
屬性。URL中允許使用表達(dá)式的URL參數(shù),設(shè)置多個(gè)參數(shù)將以,
分隔。
URL路徑中也可以使用變量模板,即可以設(shè)置rest風(fēng)格的參數(shù)。/
開頭的相對(duì)URL將自動(dòng)以應(yīng)用上下文名稱為前綴。如果cookie未啟用或還未知道,可能會(huì)在相對(duì)URL中添加;jsessionid=...
后綴以便保留會(huì)話。這被稱為URL重寫。
th:href
屬性允許在模板中有一個(gè)靜態(tài)的href
屬性,這樣在直接打開原型模板時(shí),模板鏈接可以被導(dǎo)航。
ThymeleafController
中新增以下方法:
@GetMapping("/url") public String url(Model model) { model.addAttribute("user", new User(1L, "趙云", "qwe123")); model.addAttribute("url", "/user/update"); return "url"; }
效果:
從上到下依次點(diǎn)擊5個(gè)鏈接和提交表單的結(jié)果:
(4)字面量
字面量(Literals)分為:
- 文本文字(Text literals):包含在單引號(hào)之間的字符串,可以包含任何字符,其中的單引號(hào)需要\'轉(zhuǎn)義。
- 數(shù)字字面量(Number literals):數(shù)字。
- 布爾字面量(Boolean literals):包含true和false。
- null字面量(The null literal):null。
- 文本符號(hào)(Literal tokens):數(shù)字,布爾和null字面量實(shí)際是文本符號(hào)的特殊情況,文本符號(hào)不需要引號(hào)包圍,只允許使用字母(A-Z和a-z)、數(shù)字(0-9)、括號(hào)、點(diǎn)(.)、連字符(-)和下劃線(_)。
模板literal.html
如下:
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>字面量</title> </head> <body> <div> <ul> <li> <p><span>文本文字:</span><span th:text="'Hello World'">⽂本文字只是包含在單引號(hào)之間的字符串,可以包含任何字符,其中的單引號(hào)需要\'轉(zhuǎn)義</span></p> </li> <li> <p><span>數(shù)字字面量:</span><span th:text="2020 + 1">數(shù)字字面量就是數(shù)字</span></p> </li> <li> <p><span>布爾字面量:</span><span th:if="${flag} == false">布爾字⾯量包含true和false</span></p> </li> <li> <p><span>null字面量:</span><span th:if="${flag} != null">Thymeleaf標(biāo)準(zhǔn)表達(dá)式語(yǔ)法中也可以使⽤null字⾯量</span></p> </li> <li> <p><span>文本符號(hào):</span><span th:text="Hello_.-._World">數(shù)字,布爾和null字面量實(shí)際上是⽂本符號(hào)的特殊情況</span></p> </li> </ul> </div> </body> </html>
ThymeleafController
中新增以下方法:
@GetMapping("/literal") public String literal(Model model) { model.addAttribute("flag", false); return "literal"; }
效果:
(5)文本操作
這里的文本操作包含:
- 追加文本(Appending texts),即字符串連接:無論是文本常量還是表達(dá)式結(jié)果都可以使用
+
運(yùn)算符進(jìn)行拼接。 - 字面替換(Literal substitutions):字面替換可以輕松地對(duì)包含變量值的字符串進(jìn)行格式化,而不需要在字面后加
+
,這些替換必需用|
包圍。使用字面替換也可以實(shí)現(xiàn)和追加文本相同的效果。
模板text.html
如下:
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>文本操作(字符串連接)</title> </head> <body> <div> <ul> <li> <p><span>方式1(+):</span><span th:text="'username: ' + ${user.username} + ', password: ' + ${user.password}"></span></p> </li> <li> <p><span>方式2(|):</span><span th:text="|username: ${user.username}, password: ${user.password}|"></span></p> </li> <li> <!-- 只有變量或消息表達(dá)式(${},*{},#{})才允許包含在||中 --> <p><span>方式3(+與|混合):</span><span th:text="'username: ' + ${user.username} + |, password: ${user.password}|"></span></p> </li> <li> <p><span>方式4(#strings.concat):</span><span th:text="${#strings.concat('username: ', user.username, ', password: ', user.password)}"></span></p> </li> <li> <p><span>方式5(#strings.append):</span><span th:text="${#strings.append('username: ' + user.username, ', password: ' + user.password)}"></span></p> </li> <li> <p><span>方式6(#strings.prepend):</span><span th:text="${#strings.prepend(', password: ' + user.password, 'username: ' + user.username)}"></span></p> </li> <li> <p><span>方式7(#strings.arrayJoin):</span><span th:text="${#strings.arrayJoin(new String[] {'username: ', user.username, ', password: ', user.password}, '')}"></span></p> </li> </ul> </div> </body> </html>
ThymeleafController
中新增以下方法:
@GetMapping("/text") public String text(Model model) { model.addAttribute("user", new User(1L, "趙云", "qwe123")); return "text"; }
效果:
(6)運(yùn)算符
運(yùn)算符:
- 算數(shù)運(yùn)算符:
+
、-
、*
、/
(div
)、%
(mod
)。 - 比較運(yùn)算符:
>
(gt
)、<
(lt
)、>=
(ge
)、<=
(le
)。 - 等值運(yùn)算符:
==
(eq
)、!=
(ne
)。 - 布爾運(yùn)算符:
and
、or
、!
(not
)。
模板operation.html
如下:
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>運(yùn)算符</title> </head> <body> <p th:text="|x=${x}, y=${y}|"></p> <p>算術(shù)運(yùn)算符:+、-、*、/(div)、%(mod)</p> <div> <ul> <li> <p><span>(y + x % 3) * (y - x / 2) :</span><span th:text="(${y} + ${x} % 3) * (${y} - ${x} / 2)"></span></p> </li> <li> <!-- 運(yùn)算符也可以在OGNL變量表達(dá)式本身中應(yīng)⽤(這種情況下由OGNL解析執(zhí)⾏,⽽不是Thymeleaf標(biāo)準(zhǔn)表達(dá)式引擎來解析執(zhí)⾏) --> <p><span>(x * 5 + 8 div y) mod (x - y) :</span><span th:text="${(x * 5 + 8 div y) mod (x - y)}"></span></p> </li> </ul> </div> <p>比較和等值運(yùn)算符:>(gt)、<(lt)、>=(ge)、<=(le)、==(eq)、!=(ne)</p> <div> <ul> <li> <p><span>x > 5:</span><span th:text="${x} > 5"></span></p> </li> <li> <p><span>y le 2:</span><span th:text="${y le 2}"></span></p> </li> <li> <p><span>(x * y) < 50:</span><span th:text="${(x * y) < 50}"></span></p> </li> <li> <p><span>y ge x:</span><span th:text="${y} ge ${x}"></span></p> </li> <li> <p><span>x == y:</span><span th:text="${x == y}"></span></p> </li> <li> <p><span>x ne y:</span><span th:text="${x} ne ${y}"></span></p> </li> </ul> </div> <p>布爾運(yùn)算符:and、or、!(not)</p> <div> <ul> <li> <p><span>y lt x and -x gt -y:</span><span th:text="${y} lt ${x} and ${-x} gt ${-y}"></span></p> </li> <li> <p><span>-x <= -y or y >= x:</span><span th:text="${-x <= -y or y >= x}"></span></p> </li> <li> <p><span>!(x != y):</span><span th:text="${!(x != y)}"></span></p> </li> <li> <p><span>not (x eq y):</span><span th:text="${not (x eq y)}"></span></p> </li> </ul> </div> </body> </html>
ThymeleafController
中新增以下方法:
@GetMapping("/operation") public String operator(Model model) { model.addAttribute("x", 10); model.addAttribute("y", 3); return "operation"; }
效果:
(7)條件表達(dá)式
條件表達(dá)式:
- If-then:
(if) ? (then)
。if
表達(dá)式結(jié)果為true
,則條件表達(dá)式結(jié)果為then
表達(dá)式結(jié)果,否則為null。 - If-then-else:
(if) ? (then) : (else)
。if
表達(dá)式結(jié)果為true
,則條件表達(dá)式結(jié)果為then
表達(dá)式結(jié)果,否則為else
表達(dá)式結(jié)果。 - Default(默認(rèn)表達(dá)式):
(value) ?: (defaultvalue)
。value
不為null,則結(jié)果為value
,否則結(jié)果為defaultvalue
。
模板conditional-expr.html
如下:
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>條件表達(dá)式、默認(rèn)表達(dá)式、_符號(hào)</title> </head> <body> <p th:text="|grade: ${grade}, age: ${age}|"></p> <div> <ul> <li> <!-- (if) ? (then) : (else) --> <p><span>成績(jī)是否及格:</span><span th:text="${grade >= 60} ? '及格' : '不及格'"></span></p> </li> <li> <!-- (if) ? (then),else表達(dá)式可以省略,在這種情況下,如果條件為false,則返回null值 --> <p><span>成績(jī)是否是正常數(shù)據(jù):</span><span th:text="${grade >= 0 and grade <= 100} ? '正常數(shù)據(jù)'"></span></p> </li> <li> <!-- 條件表達(dá)式可以使⽤括號(hào)嵌套 --> <p><span>成績(jī)對(duì)應(yīng)的級(jí)別:</span><span th:text="${grade >= 0 and grade <= 100} ? (${grade >= 60} ? (${grade} >= 70 ? (${grade >= 90} ? '優(yōu)' : '良') : '差') : '不及格') : '無效數(shù)據(jù)'"></span></p> </li> <li> <!-- 默認(rèn)表達(dá)式 第一個(gè)表達(dá)式結(jié)果不為null,則結(jié)果使用第一個(gè)表達(dá)式的值,結(jié)果為null,則使用第二個(gè)表達(dá)式 --> <p><span>年齡:</span><span th:text="${age} ?: '沒有年齡數(shù)據(jù)'"></span></p> </li> <li> <p><span>默認(rèn)表達(dá)式嵌套示例:</span><span th:text="${age} ?: (${grade} ?: '年齡和成績(jī)數(shù)據(jù)都不存在')"></span></p> </li> <li> <!-- _符號(hào)指定表達(dá)式不處理任何結(jié)果,這允許開發(fā)⼈員使⽤原型⽂本作為默認(rèn)值 --> <p><span>年齡:</span><span th:text="${age} ?: _">沒有年齡數(shù)據(jù)</span></p> </li> </ul> </div> </body> </html>
ThymeleafController
中新增以下方法:
@GetMapping("/conditional/expr") public String conditionExpr(Model model) { model.addAttribute("grade", 85); model.addAttribute("age", null); return "conditional-expr"; }
效果:
grade
設(shè)置為-1,age
設(shè)置為20。效果如下:
2.設(shè)置屬性
使用th:attr
屬性可以設(shè)置標(biāo)簽的任何屬性值,th:attr
只需要通過一個(gè)表達(dá)式將值賦給對(duì)應(yīng)的屬性,并且還可以通過,
分隔的形式設(shè)置多個(gè)屬性值。不過使用th:attr
設(shè)置屬性不太優(yōu)雅,所以用的不多,一般使用其他th:*屬性的形式設(shè)置指定屬性,例如要設(shè)置value
屬性,可以使用th:value
,要設(shè)置action
屬性,可以使用th:action
,要設(shè)置href
屬性,可以使用th:href
,具體都有哪些屬性可以這樣設(shè)置可以參考官方文檔。
th:attrprepend
和th:attrappend
可以給屬性設(shè)置前綴和后綴。Thymeleaf標(biāo)準(zhǔn)方言中還有兩個(gè)特定的附加屬性th:classappend
和th:styleappend
,用于將CSS的class或style樣式追加到元素中,而不覆蓋現(xiàn)有屬性。
HTML中有布爾屬性這個(gè)概念,布爾屬性沒有值,并且一旦這個(gè)布爾屬性存在則意味著屬性值為true。但是在XHTML中,這些屬性只取它本身作為屬性值。例如checked
屬性。Thymeleaf標(biāo)準(zhǔn)方言允許通過計(jì)算條件表達(dá)式的結(jié)果來設(shè)置這些屬性的值,如果條件表達(dá)式結(jié)果為true,則該屬性將被設(shè)置為其固定值,如果評(píng)估為false,則不會(huì)設(shè)置該屬性。
Thymeleaf支持使用HTML5自定義屬性語(yǔ)法data-{prefix}-{name}
來處理模板,這不需要使用任何命名空間。Thymeleaf使這種語(yǔ)法自動(dòng)適用于所有的方言(不僅僅是標(biāo)準(zhǔn)的方法)。
模板attr.html
如下:
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>設(shè)置屬性</title> </head> <body> <div> <p>設(shè)置單個(gè)任何屬性:<input type="submit" value="提交" th:attr="value=${success}"></p> <!-- th:attr可以以逗號(hào)分隔的形式來設(shè)置多個(gè)屬性值 --> <p>設(shè)置多個(gè)任何屬性:<input type="submit" value="提交" th:attr="value=${success},class='btn btn-primary'"></p> <p>設(shè)置單個(gè)指定屬性:<input type="submit" value="提交" th:value="${success}"></p> <p>設(shè)置多個(gè)指定屬性:<input type="submit" value="提交" th:value="${success}" th:class="'btn btn-primary'"></p> <!-- th:attrappend設(shè)置后綴 --> <p>設(shè)置屬性后綴:<input type="submit" value="提交" th:attrappend="value=${' ' + success}"></p> <!-- th:attrprepend設(shè)置前綴 --> <p>設(shè)置屬性前綴:<input type="submit" value="提交" th:attrprepend="value=${success + ' '}"></p> <!-- th:classappend追加class樣式 --> <p>追加class樣式:<input type="submit" value="提交" class='btn btn-primary' th:classappend="'btn-warning'"></p> <!-- th:styleappend追加style樣式 --> <p>追加style樣式:<input type="submit" value="提交" style="text-align: left" th:styleappend="'color: green'"></p> <!-- 如果條件表達(dá)式結(jié)果為true,則該屬性將被設(shè)置為其固定值,如果結(jié)果為false,則不會(huì)設(shè)置該屬性 --> <p>設(shè)置布爾屬性checked:<input type="checkbox" name="active" th:checked="${active}"></p> <!-- data-{prefix}-{name}語(yǔ)法是在HTML5中編寫⾃定義屬性的標(biāo)準(zhǔn)⽅式,不需要使⽤任何命名空間 Thymeleaf使這種語(yǔ)法自動(dòng)適用于所有的方言(不僅僅是標(biāo)準(zhǔn)的方法) --> <p>使用HTML5自定義屬性語(yǔ)法來處理模版:<span data-th-text="${success}"></span></p> </div> </body> </html>
ThymeleafController
中新增以下方法:
@GetMapping("/attr") public String attr(Model model) { model.addAttribute("success", "成功"); model.addAttribute("active", true); return "attr"; }
效果:
f12查看源碼可見屬性設(shè)置成功:
active
設(shè)置為false。checkbox沒有選中,查看源碼也沒有設(shè)置checked
屬性:
3.條件判斷
th:if
屬性可以通過判斷一個(gè)條件是否滿足,來決定是否將模板片段顯示在結(jié)果中,只有滿足條件才將模板片段顯示在結(jié)果中。而th:unless
屬性則正好與th:if
屬性相反。通過th:switch
和th:case
可以在模板中使用一種與Java中的Swicth語(yǔ)句等效的結(jié)構(gòu)有條件地顯示模板內(nèi)容。
模板conditional.html
如下:
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>條件判斷</title> </head> <body> <p th:text="|age: ${age}, userLevel: ${userLevel}, rank: ${rank}|"></p> <div th:if="${age} >= 18 and ${userLevel} eq 6"> <span>年齡大于18并且用戶等級(jí)等于6,則顯示此元素</span> </div> <div th:unless="!(${age} < 18 or ${userLevel} ne 6)"> <span>與if條件判斷相反,年齡小于18或用戶等級(jí)不等于6,則顯示此元素</span> </div> <div th:if="'null'"> <span>表達(dá)式的值不為null,th:if判定此表達(dá)式的值為true</span> </div> <div th:if="null"> <span>表達(dá)式的值為null,th:if判定此表達(dá)式的值為false</span> </div> <div th:if="${age}"> <span>值是數(shù)字并且不為0,判定此表達(dá)式的值為true</span> </div> <div th:if="0"> <span>值是數(shù)字但為0,判定此表達(dá)式的值為false</span> </div> <div th:if="A"> <span>值是一個(gè)字符并且不為0,判定此表達(dá)式的值為true</span> </div> <div th:if="'string'"> <span>值是一個(gè)字符串,不是false,off或no,判定此表達(dá)式的值為true</span> </div> <div th:if="'false'"> <span>值是字符串false,判定此表達(dá)式的值為false</span> </div> <div th:if="'off'"> <span>值是字符串off,判定此表達(dá)式的值為false</span> </div> <div th:if="'no'"> <span>值是字符串no,判定此表達(dá)式的值為false</span> </div> <hr/> <div th:switch="${rank}"> <span th:case="1">青銅</span> <span th:case="2">白銀</span> <span th:case="3">黃金</span> <span th:case="4">鉑金</span> <span th:case="5">鉆石</span> <span th:case="6">王者</span> <span th:case="*">無段位</span> </div> </body> </html>
注意:
如果表達(dá)式的值不為null。(如果表達(dá)式的值為null,
th:if
屬性不僅僅以布爾值作為判斷條件。它將按照以下規(guī)則判定指定的表達(dá)式值為true:th:if
判定此表達(dá)式的值為false。)
如果值為布爾值,則為true。如果值是數(shù)字且不為0。
如果值是一個(gè)字符且不為0。如果值是一個(gè)字符串,不是"false",“off"或"no”。
如果值不是布爾值,數(shù)字,字符或字符串。同一個(gè)Switch語(yǔ)句中只要第一個(gè)
th:case
的值為true,則其他的th:case
屬性將被視為false。Switch語(yǔ)句的default選項(xiàng)指定為th:case=“*”
。
ThymeleafController
中新增以下方法:
@GetMapping("/conditional") public String condition(Model model) { Map<String, Object> map = new HashMap<>(); map.put("age", 10); map.put("userLevel", 6); map.put("rank", 5); model.addAllAttributes(map); return "conditional"; }
效果:
age
設(shè)置為20,userLevel
設(shè)置為6,rank
設(shè)置為0。效果如下:
4.循環(huán)迭代
使用th:each
屬性可以迭代以下對(duì)象:
- 任何實(shí)現(xiàn)
java.util.Iterable
接口的對(duì)象。 - 任何實(shí)現(xiàn)
java.util.Enumeration
接口的對(duì)象。 - 任何實(shí)現(xiàn)
java.util.Iterator
接口的對(duì)象。其值將被迭代器返回,不需要在內(nèi)存中緩存所有值。 - 任何實(shí)現(xiàn)
java.util.Map
接口的對(duì)象。迭代map時(shí),迭代變量將是java.util.Map.Entry
類型。 - 任何數(shù)組。
- 任何其將被視為包含對(duì)象本身的單值列表。
(1)迭代List
模板each-list.html
如下:
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>循環(huán)迭代List</title> </head> <body> <table> <thead> <tr> <th>id</th> <th>username</th> <th>password</th> <th>index</th> <th>count</th> <th>size</th> <th>current</th> <th>even</th> <th>odd</th> <th>first</th> <th>last</th> </tr> </thead> <tbody> <!-- ${users}為迭代表達(dá)式或被迭代變量,userStat為狀態(tài)變量,user為迭代變量 --> <tr th:each="user,userStat : ${users}"> <td th:text="${user.id}"></td> <td th:text="${user.username}"></td> <td th:text="${user.password}"></td> <!-- 當(dāng)前迭代索引,從0開始 --> <td th:text="${userStat.index}"></td> <!-- 當(dāng)前迭代索引,從1開始 --> <td th:text="${userStat.count}"></td> <!-- 被迭代變量中元素總數(shù) --> <td th:text="${userStat.size}"></td> <!-- 每次迭代的迭代變量 --> <td th:text="${userStat.current}"></td> <!-- 布爾值,當(dāng)前迭代是否是奇數(shù),從0算起 --> <td th:text="${userStat.even}"></td> <!-- 布爾值,當(dāng)前迭代是否是偶數(shù),從0算起 --> <td th:text="${userStat.odd}"></td> <!-- 布爾值,當(dāng)前迭代是否是第一個(gè) --> <td th:text="${userStat.first}"></td> <!-- 布爾值,當(dāng)前迭代是否是最后一個(gè) --> <td th:text="${userStat.last}"></td> </tr> </tbody> </table> </body> </html>
狀態(tài)變量是在使用
th:each
時(shí)Thymeleaf提供的一種用于跟蹤迭代狀態(tài)的機(jī)制。狀態(tài)變量在th:each
屬性中通過在迭代變量之后直接寫其名稱來定義,用,
分隔。與迭代變量一樣,狀態(tài)變量的作用范圍也是th:each
屬性所在標(biāo)簽定義的代碼片段中。如果沒有顯式地設(shè)置狀態(tài)變量,Thymeleaf總是會(huì)創(chuàng)建一個(gè)名為迭代變量名加上Stat
后綴的狀態(tài)變量。
ThymeleafController
中新增以下方法:
@GetMapping("/each/list") public String eachList(ModelMap model) { List<User> users = new ArrayList<>(); users.add(new User(1L, "劉備", "123132")); users.add(new User(2L, "關(guān)羽", "321231")); users.add(new User(3L, "張飛", "213312")); model.addAttribute("users", users); return "each-list"; }
效果:
(2)迭代Map
模板each-map.html
如下:
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>循環(huán)迭代Map</title> </head> <body> <table> <thead> <tr> <th>id</th> <th>username</th> <th>password</th> <th>key</th> <th>index</th> <th>count</th> <th>size</th> <th>current</th> <th>even</th> <th>odd</th> <th>first</th> <th>last</th> </tr> </thead> <tbody> <tr th:each="map,mapStat : ${userMap}"> <td th:text="${mapStat.current.value.id}"></td> <td th:text="${mapStat.current.value.username}"></td> <td th:text="${mapStat.current.value.password}"></td> <td th:text="${mapStat.current.key}"></td> <td th:text="${mapStat.index}"></td> <td th:text="${mapStat.count}"></td> <td th:text="${mapStat.size}"></td> <td th:text="${mapStat.current}"></td> <td th:text="${mapStat.even}"></td> <td th:text="${mapStat.odd}"></td> <td th:text="${mapStat.first}"></td> <td th:text="${mapStat.last}"></td> </tr> </tbody> </table> <hr/> <table> <thead> <tr> <th>id</th> <th>username</th> <th>password</th> <th>key</th> <th>index</th> <th>count</th> <th>size</th> <th>current</th> <th>even</th> <th>odd</th> <th>first</th> <th>last</th> </tr> </thead> <tbody> <tr th:each="map,mapStat : ${userMap}"> <td th:text="${map.value.id}"></td> <td th:text="${map.value.username}"></td> <td th:text="${map.value.password}"></td> <td th:text="${map.key}"></td> <td th:text="${mapStat.index}"></td> <td th:text="${mapStat.count}"></td> <td th:text="${mapStat.size}"></td> <td th:text="${mapStat.current}"></td> <td th:text="${mapStat.even}"></td> <td th:text="${mapStat.odd}"></td> <td th:text="${mapStat.first}"></td> <td th:text="${mapStat.last}"></td> </tr> </tbody> </table> </body> </html>
ThymeleafController
中新增以下方法:
@GetMapping("/each/map") public String eachMap(Model model) { Map<String, Object> map = new HashMap<>(16); map.put("user1", new User(1L, "劉備", "123132")); map.put("user2", new User(2L, "關(guān)羽", "321231")); map.put("user3", new User(3L, "張飛", "213312")); model.addAttribute("userMap", map); return "each-map"; }
效果:
(3)迭代Array
模板each-array.html
如下:
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>循環(huán)迭代Array</title> </head> <body> <table> <thead> <tr> <th>id</th> <th>username</th> <th>password</th> <th>index</th> <th>count</th> <th>size</th> <th>current</th> <th>even</th> <th>odd</th> <th>first</th> <th>last</th> </tr> </thead> <tbody> <!-- ${users}為迭代表達(dá)式或被迭代變量,userStat為狀態(tài)變量,user為迭代變量 --> <tr th:each="user,userStat : ${users}"> <td th:text="${user.id}"></td> <td th:text="${user.username}"></td> <td th:text="${user.password}"></td> <!-- 當(dāng)前迭代索引,從0開始 --> <td th:text="${userStat.index}"></td> <!-- 當(dāng)前迭代索引,從1開始 --> <td th:text="${userStat.count}"></td> <!-- 被迭代變量中元素總數(shù) --> <td th:text="${userStat.size}"></td> <!-- 每次迭代的迭代變量 --> <td th:text="${userStat.current}"></td> <!-- 布爾值,當(dāng)前迭代是否是奇數(shù),從0算起 --> <td th:text="${userStat.even}"></td> <!-- 布爾值,當(dāng)前迭代是否是偶數(shù),從0算起 --> <td th:text="${userStat.odd}"></td> <!-- 布爾值,當(dāng)前迭代是否是第一個(gè) --> <td th:text="${userStat.first}"></td> <!-- 布爾值,當(dāng)前迭代是否是最后一個(gè) --> <td th:text="${userStat.last}"></td> </tr> </tbody> </table> </body> </html>
ThymeleafController
中新增以下方法:
@GetMapping("/each/array") public String eachArray(Model model) { User[] users = {new User(1L, "劉備", "123132"), new User(2L, "關(guān)羽", "321231"), new User(3L, "張飛", "213312")}; model.addAttribute("users", users); return "each-array"; }
效果:
5.模板布局
(1)引用模板片段
th:fragment
屬性可以用來定義模板片段,th:insert
、th:replace
和th:include
(Thymeleaf3.0不再推薦使用)屬性可以引用模板片段。
首先創(chuàng)建一個(gè)名為footer.html
的模板文件用來包含模板片段,然后定義一個(gè)名為copy1
的片段:
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>footer</title> </head> <body> <div th:fragment="copy1"> © 2021 </div> </body> </html>
然后在名為layout.html
的模板中引用該片段:
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>引用模板片段</title> </head> <body> <div th:insert="~{footer :: copy1}"></div> <div th:replace="~{footer :: copy1}"></div> <div th:include="~{footer :: copy1}"></div> </body> </html>
ThymeleafController
中新增以下方法:
@GetMapping("/layout") public String layout(Model model) { return "layout"; }
效果:
引用模板片段語(yǔ)法中的~{}
是可選的,以下代碼與之前的等價(jià):
<div th:insert="footer :: copy1"></div> <div th:replace="footer :: copy1"></div> <div th:include="footer :: copy1"></div>
效果:
th:insert
、th:replace
和th:include
都能引用模板片段,直接在頁(yè)面中還看不出三者的區(qū)別。為了更明顯地看出區(qū)別,在footer.html
模板中新增以下片段:
<footer th:fragment="copy2" > © 2020-2023 </footer>
然后在layout.html
模板中分別使用th:insert
、th:replace
和th:include
進(jìn)行引用:
<div th:insert="footer :: copy2">th:insert將指定片段插⼊到指定宿主標(biāo)簽的標(biāo)簽體中</div> <div th:replace="footer :: copy2">th:replace實(shí)際上⽤指定的⽚段替換其宿主標(biāo)簽</div> <div th:include="footer :: copy2">th:include只插⼊此⽚段的內(nèi)容到指定宿主標(biāo)簽的標(biāo)簽體中</div>
效果:
按F12查看源碼可以看出區(qū)別:
所以三者區(qū)別為:
th:insert
將指定片段插入到指定宿主標(biāo)簽的標(biāo)簽體中。th:replace
實(shí)際上用指定的片段替換其宿主標(biāo)簽。th:include
只插入此片段的內(nèi)容到指定宿主標(biāo)簽的標(biāo)簽體中。
引用模板片段的規(guī)范語(yǔ)法有以下三種格式:
~{templatename::selector}
:包含在名為templatename的模板上通過指定的selector匹配的片段。selector可以只是一個(gè)片段名稱。~{templatename}
:包含名為templatename的整個(gè)模板。~{::selector}
或~{this::selector}
:包含在同一模板中與指定selector匹配的片段。如果在表達(dá)式出現(xiàn)的模板上沒有找到,模板調(diào)用(插入)的堆棧會(huì)向最初處理的模板(root)遍歷,直到selector在某個(gè)層次上匹配。
templatename和selector都可以是表達(dá)式。模板片段中可以包含任何th:*屬性,一旦在目標(biāo)模板中引用了片段,這些屬性將被計(jì)算并且它們能夠引用目標(biāo)模板中定義的任何上下文變量。
通過th:replace="~{footer}"
可以引用整個(gè)footer.html
:
<div th:replace="~{footer}">引用名為footer的整個(gè)模板</div>
效果:
在layout.html
模板中新增以下幾個(gè)片段:
<div th:fragment="frag"> <p>~{:: selector}或~{this :: selector}包含在同⼀模板中的匹配指定選擇器的⽚段</p> </div> <div> <p>文本輸入框:<input type="text" value="輸入內(nèi)容"></p> </div> <input type="submit" value="提交">
在layout.html
模板中引用frag和input片段:
<div th:insert="~{:: frag}">引用當(dāng)前模板中的片段</div> <div th:insert="~{this :: input}">引用當(dāng)前模板中的片段</div>
效果:
selector寫成一個(gè)條件表達(dá)式,可以通過條件來決定引用的片段:
<div th:insert="~{footer :: (${flag} ? copy1 : copy2)}">模板名和選擇器都可以是表達(dá)式</div>
將變量flag
設(shè)置到Model中:
model.addAttribute("flag", true);
效果:
flag
設(shè)置為fasle時(shí)的效果:
由于標(biāo)簽選擇器的強(qiáng)大功能,沒有使用th:fragment
屬性的片段可以通過id
屬性來引用。在footer.html
模板中新增以下片段:
<div id="copy-section"> <p>沒有使用th:fragment屬性的片段可以通過id屬性來引用</p> </div>
在layout.html
模板中引用該片段:
<div th:insert="~{footer :: #copy-section}">可以通過id屬性來引⽤沒有th:fragment屬性的⽚段</div>
效果:
(2)參數(shù)化的模板片段
th:fragment
定義的片段可以指定一組參數(shù)。在footer.html
模板中新增以下片段:
<div th:fragment="frag (var1,var2)"> <p th:text="${var1} + ' - ' + ${var2}">th:fragment定義的⽚段可以指定⼀組參數(shù)</p> </div>
在layout.html
模板中分別用以下兩種語(yǔ)法引用該片段:
<!-- 引用定義了參數(shù)的模板片段的兩種語(yǔ)法 --> <div th:insert="footer :: frag (${var1},${var2})">引用定義了參數(shù)的模板片段語(yǔ)法1</div> <div th:insert="footer :: frag (var1=${var1},var2=${var2})">引用定義了參數(shù)的模板片段語(yǔ)法2,可以改變參數(shù)順序</div>
將變量var1
和var2
設(shè)置到Model中:
model.addAttribute("var1", "參數(shù)1"); model.addAttribute("var2", "參數(shù)2");
效果:
即使片段沒有定義參數(shù),也可以調(diào)用片段中的局部變量。在footer.html
模板中新增以下片段:
<div th:fragment="frag2"> <p th:text="${var1} + ' * ' + ${var2}">沒有定義參數(shù)的模板片段</p> </div>
在layout.html
模板中分別通過以下語(yǔ)法調(diào)用片段中的局部變量:
<!-- 沒有定義參數(shù)的模板片段中的局部變量,可以使用以下語(yǔ)法調(diào)用,以下兩種寫法等價(jià) --> <div th:insert="footer :: frag2 (var1=${var1},var2=${var2})">沒有定義參數(shù)的模板片段中的局部變量的調(diào)用語(yǔ)法1</div> <div th:insert="footer :: frag2" th:with="var1=${var1},var2=${var2}">沒有定義參數(shù)的模板片段中的局部變量的調(diào)用語(yǔ)法2</div>
引用定義參數(shù)的模板片段的兩種語(yǔ)法中,第一種語(yǔ)法不能調(diào)用沒有定義參數(shù)的片段中的局部變量,只有第二種語(yǔ)法能調(diào)用。
注意:片段的局部變量規(guī)范 - 無論是否具有參數(shù)簽名 - 都不會(huì)導(dǎo)致上下文在執(zhí)行前被清空。片段仍然能訪問調(diào)用模板中正在使用的每個(gè)上下文變量。
效果:
使用th:assert
可以進(jìn)行模板內(nèi)部斷言,它可以指定逗號(hào)分隔的表達(dá)式列表,如果每個(gè)表達(dá)式的結(jié)果都為true,則正確執(zhí)行,否則引發(fā)異常。在footer.html
模板中新增以下片段:
<div th:fragment="assert-test (user)" th:assert="${user.id != null},${!#strings.isEmpty(user.username)},${!#strings.isEmpty(user.password)}"> <p th:text="${#strings.toString(user)}">⽤th:assert進(jìn)⾏模版內(nèi)部斷⾔ </p> </div>
在layout.html
模板中引用該片段:
<!-- 引用帶有斷言的模板片段 --> <div th:insert="footer :: assert-test (${user})"></div>
將變量user
設(shè)置到Model中:
model.addAttribute("user", new User(1L, "趙云", "qwe123"));
效果:
只將id設(shè)置為null,訪問模板出現(xiàn)以下異常:
只將username設(shè)置為空,訪問模板出現(xiàn)以下異常:
只將password設(shè)置為空,訪問模板出現(xiàn)以下異常:
(3)靈活布局
通過片段表達(dá)式不僅可以指定文本類型、數(shù)字類型、對(duì)象類型的參數(shù),還可以指定標(biāo)記片段作為參數(shù)。這種方式可以使模板布局變得非常靈活。
下面進(jìn)行一個(gè)頁(yè)面布局的簡(jiǎn)單模擬測(cè)試,首先在templates
下新建一個(gè)layout
目錄,用于存放一些組件模板。
layout/footer.html
:
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>footer</title> </head> <body> <footer th:fragment="footer"> <h1>模板布局頁(yè)面頁(yè)腳</h1> </footer> </body> </html>
layout/header.html
:
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>header</title> </head> <body> <header th:fragment="header"> <h1>模板布局頁(yè)面頭部</h1> </header> </body> </html>
layout/left.html
:
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>left</title> </head> <body> <div th:fragment="left"> <h1>模板布局頁(yè)面左側(cè)菜單</h1> </div> </body> </html>
在templates
下新建一個(gè)基礎(chǔ)模板base.html
:
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head th:fragment="common_header (title)"> <meta charset="UTF-8"> <title th:replace="${title}">common title</title> </head> <body> <div th:fragment="common_div (header,left,footer)"> <div th:replace="${header}"><h1>common header</h1></div> <div th:replace="${left}"><h1>common left</h1></div> <p>common content</p> <div th:replace="${footer}"><h1>common footer</h1></div> </div> </body> </html>
然后在名為layout-home.html
的模板中引用base.html
中的片段:
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head th:replace="base :: common_header(~{:: title})"> <title>模板布局主頁(yè)</title> </head> <body> <div th:replace="base :: common_div (~{layout/header :: header},~{layout/left :: left},~{layout/footer :: footer})"></div> </body> </html>
ThymeleafController
中新增以下方法:
@GetMapping("/layout/home") public String layoutHome(Model model) { return "layout-home"; }
效果:
使用特殊片段表達(dá)式~{}
可以指定沒有標(biāo)記。在layout-home.html
中通過以下代碼引用base.html
中的片段:
<div th:replace="base :: common_div (~{layout/header :: header},~{layout/left :: left},~{})"></div>
效果:
_
符號(hào)也可以用作片段參數(shù)。在layout-home.html
中通過以下代碼引用base.html
中的片段:
<div th:replace="base :: common_div (~{layout/header :: header},~{layout/left :: left},_)"></div>
_
符號(hào)導(dǎo)致common_div片段中的th:replace="${footer}"
不被執(zhí)行,從而該div標(biāo)簽使用原型文本。
效果:
~{}
和_
符號(hào)可以通過簡(jiǎn)單優(yōu)雅的方式實(shí)現(xiàn)執(zhí)行片段的條件插入。在layout-home.html
中通過以下代碼引用base.html
中的片段:
<div th:replace="base :: common_div (${condition} ? ~{layout/header :: header} : ~{},${condition} ? ~{layout/left :: left} : ~{},${condition} ? ~{layout/footer :: footer} : ~{})"></div>
參數(shù)中的每一個(gè)
condition
條件可以根據(jù)實(shí)際業(yè)務(wù)需求靈活控制。這里為了測(cè)試方便,都使用的相同條件。
將變量condition
設(shè)置到Model中:
model.addAttribute("condition", false);
效果:
在layout-home.html
中通過以下代碼引用base.html
中的片段:
<div th:replace="base :: common_div (${condition} ? ~{layout/header :: header} : _,${condition} ? ~{layout/left :: left} : _,${condition} ? ~{layout/footer :: footer} : _)"></div>
效果:
條件也可以不在參數(shù)中進(jìn)行判斷,還在common_div片段的th:replace
屬性中進(jìn)行判斷。在layout-home.html
中通過以下代碼引用base.html
中的片段:
<div th:replace="base :: common_div (~{layout/header :: header},~{layout/left :: left},~{layout/footer :: footer},${condition})"></div>
base.html
中的common_div片段:
<div th:fragment="common_div (header,left,footer,condition)"> <div th:replace="${condition} ? ${header} : _"><h1>Common header</h1></div> <div th:replace="${condition} ? ${left}: _"><h1>Common left</h1></div> <p>Common content</p> <div th:replace="${condition} ? ${footer}: _"><h1>Common footer</h1></div> </div>
效果:
6.局部變量
Thymeleaf的局部變量是指定義在模板片段中的變量,該變量的作用域?yàn)樗谀0迤巍?code>th:each中的迭代變量就是一個(gè)局部變量,作用域?yàn)?code>th:each所在的標(biāo)簽范圍,可用于該標(biāo)簽內(nèi)優(yōu)先級(jí)低于th:each
的任何其他th:*屬性,可用于該標(biāo)簽的任何子元素。使用th:with
屬性可以聲明局部變量。
在local.html
模板中使⽤th:with
屬性聲明局部變量:
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>局部變量</title> </head> <body> <!-- 使⽤th:with屬性聲明局部變量 --> <div th:with="user1=${users[0]}"> <span>user1的姓名:</span><span th:text="${user1.username}"></span> </div> </body> </html>
ThymeleafController
中新增以下方法:
@GetMapping("/local") public String local(Model model) { User[] users = {new User(1L, "劉備", "123132"), new User(2L, "關(guān)羽", "321231"), new User(3L, "張飛", "213312")}; model.addAttribute("users", users); return "local"; }
效果:
局部變量只能在聲明的標(biāo)簽內(nèi)使用。在local.html
模板中新增以下內(nèi)容:
<!-- 局部變量不能在聲明的標(biāo)簽外使用 --> <div> <span>user1的姓名:</span><span th:text="${user1.username}">張三</span> </div>
訪問模板會(huì)報(bào)錯(cuò):
可以同時(shí)定義多個(gè)局部變量。在local.html
模板中新增以下內(nèi)容:
<!-- 使⽤通常的多重賦值語(yǔ)法同時(shí)定義多個(gè)變量 --> <div th:with="user1=${users[0]},user2=${users[1]}"> <span>user1的姓名:</span><span th:text="${user1.username}"></span> <br/> <span>user2的姓名:</span><span th:text="${user2.username}"></span> </div>
效果:
th:with
屬性允許重⽤在同⼀屬性中定義的變量。在local.html
模板中新增以下內(nèi)容:
<!-- th:with屬性允許重⽤在同⼀屬性中定義的變量 --> <div> <!-- th:with的優(yōu)先級(jí)高于th:text --> <span>當(dāng)前時(shí)間:</span><span th:with="now=${#calendars.createNow()}" th:text="${#calendars.format(now, 'yyyy/MM/dd hh:mm:ss')}"></span> </div>
效果:
7.屬性優(yōu)先級(jí)
多個(gè)th:*屬性在同一個(gè)標(biāo)簽中的執(zhí)行順序由優(yōu)先級(jí)決定。所有Thymeleaf屬性都定義了一個(gè)數(shù)字優(yōu)先級(jí),以確定了它們?cè)跇?biāo)簽中執(zhí)行的順序,數(shù)字越小優(yōu)先級(jí)越高:
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 |
優(yōu)先級(jí)意味著屬性位置發(fā)生變化,也會(huì)得出相同的結(jié)果。
8.注釋和塊
(1)標(biāo)準(zhǔn)HTML/XML注釋
標(biāo)準(zhǔn)HTML/XML注釋<!-- -->
可以在Thymeleaf模板中的任何地方使用。這些注釋中的任何內(nèi)容都不會(huì)被Thymeleaf處理,并將逐字復(fù)制到結(jié)果中。
這里直接運(yùn)行項(xiàng)目訪問local.html
模板,查看模板源碼可見HTML注釋沒有被處理,保持原樣:
(2)ThymeLeaf解析器級(jí)注釋
解析器級(jí)注釋塊<!--/* */-->
在Thymeleaf解析時(shí)會(huì)將<!--/
和*/-->
之間的所有內(nèi)容從模板中刪除。當(dāng)此模板靜態(tài)打開時(shí),這些注釋塊可用于顯示代碼。
修改local.html
模板的其中一個(gè)注釋為如下內(nèi)容:
<!--/* <div> <span>user1的姓名:</span><span th:text="${user1.username}">張三</span> </div>*/-->
查看源碼可見注釋已從模板中刪除:
(3)Thymeleaf專有注釋
Thymeleaf允許定義特殊注釋塊<!--/*/ /*/-->
,在Thymeleaf解析時(shí)會(huì)將<!--/*/
和/*/-->
標(biāo)記刪除,但不刪除標(biāo)記之間的內(nèi)容。當(dāng)此模板靜態(tài)打開時(shí),會(huì)顯示注釋標(biāo)記。
修改local.html
模板的其中一個(gè)注釋為如下內(nèi)容:
<!--/*/ <div th:with="user1=${users[0]}"> <span>user1的姓名:</span><span th:text="${user1.username}"></span> </div>/*/-->
查看源碼發(fā)現(xiàn)只刪除了標(biāo)記部分,中間的內(nèi)容保留:
(4)th:block標(biāo)簽
th:block
標(biāo)簽是Thymeleaf標(biāo)準(zhǔn)方言中唯一的元素處理器。th:block
是一個(gè)允許模板開發(fā)者指定想要的任何屬性的屬性容器,Thymeleaf會(huì)執(zhí)行這些屬性并讓這個(gè)塊消失,但它的內(nèi)容保留。
模板block.html
如下:
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>th:block</title> </head> <body> <table> <th:block th:each="user : ${users}"> <tr> <td th:text="${user.id}">1</td> <td th:text="${user.username}">root</td> </tr> <tr> <td colspan="2" th:text="${user.password}">root</td> </tr> </th:block> </table> </body> </html>
使用
th:block
可以輕松地迭代同級(jí)標(biāo)簽,例如在<table>
中為每個(gè)迭代元素創(chuàng)建多個(gè)<tr>
時(shí)使用th:block
就很簡(jiǎn)單。
ThymeleafController
中新增以下方法:
@GetMapping("/block") public String block(Model model) { List<User> users = new ArrayList<>(); users.add(new User(1L, "劉備", "123132")); users.add(new User(2L, "關(guān)羽", "321231")); users.add(new User(3L, "張飛", "213312")); model.addAttribute("users", users); return "block"; }
效果:
查看源碼:
在和原型注釋塊結(jié)合時(shí)很有用:
<table> <!--/*/ <th:block th:each="user : ${users}"> /*/--> <tr> <td th:text="${user.id}">1</td> <td th:text="${user.username}">root</td> </tr> <tr> <td colspan="2" th:text="${user.password}">root</td> </tr> <!--/*/ </th:block> /*/--> </table>
效果:
9.內(nèi)聯(lián) (1)內(nèi)聯(lián)表達(dá)式
[[]]
或[()]
中的表達(dá)式為內(nèi)聯(lián)表達(dá)式,可以直接將表達(dá)式寫入HTML文本。任何在th:text
或th:utext
屬性中使用的表達(dá)式都可以出現(xiàn)在[[]]
或[()]
中。[[]]
等價(jià)于th:text
,會(huì)轉(zhuǎn)義html標(biāo)簽;[()]
等價(jià)于th:utext
,不會(huì)轉(zhuǎn)義html標(biāo)簽。
模板inline.html
如下:
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>內(nèi)聯(lián)</title> </head> <body> <h1>th:text和th:utext</h1> <p>Hello <span th:text="${user.username}">World</span> !</p> <p>Hello <span th:utext="${user.username}">World</span> !</p> <h1>內(nèi)聯(lián)表達(dá)式</h1> <!-- 會(huì)轉(zhuǎn)義html標(biāo)簽,等價(jià)于th:text --> <p>Hello [[${user.username}]] !</p> <!-- 不會(huì)轉(zhuǎn)義html標(biāo)簽,等價(jià)于th:utext --> <p>Hello [(${user.username})] !</p> </body> </html>
ThymeleafController
中新增以下方法:
@GetMapping("/inline") public String inline(Model model) { model.addAttribute("user", new User(1L, "<b>趙云</b>", "this is \"pass\" word")); return "inline"; }
效果:
注意,靜態(tài)打開模板文件時(shí),內(nèi)聯(lián)表達(dá)式會(huì)顯示出來,這樣就無法將其作為原型設(shè)計(jì)了。靜態(tài)打開inline.html
模板的效果如下:
在有些情況下可能需要禁用內(nèi)聯(lián),比如需要輸出[[]]序列時(shí)。通過th:inline="none"
可以禁用內(nèi)聯(lián)。在模板inline.html
中新增以下內(nèi)容:
<p>這是一個(gè)二維數(shù)組:[[1, 2, 3], [4, 5]]</p>
訪問模板時(shí)會(huì)報(bào)如下錯(cuò)誤:
在剛才的代碼中增加禁用內(nèi)聯(lián):
<h2>禁用內(nèi)聯(lián)</h2> <p th:inline="none">這是一個(gè)二維數(shù)組:[[1, 2, 3], [4, 5]]</p>
效果:
(2)內(nèi)聯(lián)JavaScript
使用th:inline="javascript"
啟用內(nèi)聯(lián)JavaScript。
在模板inline.html
中新增以下內(nèi)容:
<h1>內(nèi)聯(lián)JavaScript</h1> <div> <span><button onclick="showPassword()">按鈕</button></span> </div>
<script type="text/javascript" th:inline="javascript"> let password = [[${user.password}]]; console.log("password:", password); function showPassword() { alert(password); } </script>
效果:
查看源碼,可見輸出的字符串進(jìn)行了轉(zhuǎn)義,是格式正確的JavaScript字符串,因?yàn)槭褂?code>[[]]在輸出${user.password}
表達(dá)式的時(shí)候進(jìn)行了轉(zhuǎn)義:
查看Console中打印的日志:
注釋掉let password = [[${user.password}]];
,新增let password = [(${user.password})];
。查看源碼,由于[()]
不會(huì)進(jìn)行轉(zhuǎn)義,可見輸出的字符串沒有轉(zhuǎn)義,是格式錯(cuò)誤的JavaScript代碼:
查看Console,發(fā)現(xiàn)有語(yǔ)法錯(cuò)誤:
如果通過附加內(nèi)聯(lián)表達(dá)式的方式來構(gòu)建腳本的一部分,可能會(huì)需要輸出未轉(zhuǎn)義的字符串,所以這個(gè)功能也很有用。
內(nèi)聯(lián)JavaScript可以通過在注釋中包含內(nèi)聯(lián)表達(dá)式作為JavaScript自然模板。下面注釋掉let password = [(${user.password})];
,新增如下代碼:
// 在JavaScript注釋中包含(轉(zhuǎn)義)內(nèi)聯(lián)表達(dá)式,Thymeleaf將忽略在注釋之后和分號(hào)之前的所有內(nèi)容 let password = /*[[${user.password}]]*/ "default password";
查看源碼:
查看Console中打印的日志:
發(fā)現(xiàn)"default password"
確實(shí)被忽略了。以靜態(tài)方式打開模板時(shí)變量password
的值就為"default password"
了:
JavaScript內(nèi)聯(lián)表達(dá)式結(jié)果不限于字符串,還會(huì)自動(dòng)地將Strings、Numbers、Booleans、Arrays、Collections、Maps、Beans(有g(shù)etter和setter方法)這些對(duì)象序列化為JavaScript對(duì)象。下面在Controller中新增以下代碼:
Map<String, Object> map = new HashMap<>(16); map.put("user1", new User(1L, "劉備", "123132")); map.put("user2", new User(2L, "關(guān)羽", "321231")); map.put("user3", new User(3L, "張飛", "213312")); model.addAttribute("userMap", map);
script
標(biāo)簽內(nèi)新增以下代碼,Thymeleaf會(huì)將userMap對(duì)象轉(zhuǎn)換為JavaScript對(duì)象:
// userMap為一個(gè)Map對(duì)象,Thymeleaf會(huì)將其轉(zhuǎn)換為JavaScript對(duì)象 let userMap = /*[[${userMap}]]*/ null; console.log("userMap:", userMap); // 遍歷userMap for (let key in userMap) { console.log(key + ": " + "{id: " + userMap[key].id + ", username: " + userMap[key].username + ", password: " + userMap[key].password + "}"); }
查看源碼發(fā)現(xiàn)Thymeleaf已經(jīng)將其轉(zhuǎn)換為JavaScript對(duì)象:
查看Console中打印的日志:
(3)內(nèi)聯(lián)CSS
使用th:inline="css"
啟用內(nèi)聯(lián)CSS。
在模板inline.html
中新增以下內(nèi)容:
<style type="text/css" th:inline="css"> [[${element}]] { text-align: [[${align}]]; color: [[${color}]]; } </style>
將變量element
、align
和color
設(shè)置到Model中:
model.addAttribute("element", "h1"); model.addAttribute("align", "center"); model.addAttribute("color", "#2876A7");
訪問模板,對(duì)齊生效,顏色未生效:
查看源碼,發(fā)現(xiàn)color的值多了一個(gè)\
:
這是由于[[]]
會(huì)進(jìn)行轉(zhuǎn)義,所以多了一個(gè)\
。這里不需要對(duì)其轉(zhuǎn)義,所以需要使用[()]
。將代碼修改為color: [(${color})];
。訪問模板,發(fā)現(xiàn)樣式都生效了:
查看源碼,沒有多出\
了:
內(nèi)聯(lián)CSS也允許通過在注釋中包含內(nèi)聯(lián)表達(dá)式作為CSS自然模板,使CSS可以靜態(tài)和動(dòng)態(tài)的工作。將<style>
的代碼修改為如下內(nèi)容:
<style type="text/css" th:inline="css"> h1 { text-align: /*[[${align}]]*/ left; color: /*[(${color})]*/ #B60d16; } </style>
模板動(dòng)態(tài)打開時(shí)的效果:
查看源碼:
以靜態(tài)方式打開的效果:
查看源碼:
10.國(guó)際化
這里簡(jiǎn)單模擬一下國(guó)際化功能,通過語(yǔ)言切換應(yīng)用對(duì)應(yīng)語(yǔ)言的國(guó)際化配置文件。
(1)創(chuàng)建國(guó)際化配置文件
在resources/i18n
目錄下創(chuàng)建如下配置文件。
index.properties
:
user.register=注冊(cè) user.login=登錄 index.language=語(yǔ)言 index.language.chinese=中文 index.language.english=英文
index_en_US.properties
:
user.register=Register user.login=Login index.language=Language index.language.chinese=Chinese index.language.english=English
index_zh_CN.properties
:
user.register=注冊(cè) user.login=登錄 index.language=語(yǔ)言 index.language.chinese=中文 index.language.english=英文
(2)新增配置
在application.yml
中新增以下配置:
spring: messages: # 配置消息源的基本名稱,默認(rèn)為messages,這里配置為國(guó)際化配置文件的前綴 basename: i18n.index
(3)創(chuàng)建模板
模板i18n.html
如下:
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>國(guó)際化</title> </head> <body> <div> <span><button th:text="#{user.register}">注冊(cè)</button></span> <span><button th:text="#{user.login}">登錄</button></span> <span th:text="#{index.language}">語(yǔ)言</span> <a th:href="@{/index(lang='zn_CN')}" th:text="#{index.language.chinese}">中文</a> <a th:href="@{/index(lang='en_US')}" th:text="#{index.language.english}">英文</a> </div> </body> </html>
#{}
為消息表達(dá)式,用于引用消息字符串。而消息字符串通常保存在外部化文本中,消息字符串形式為key=value,通過#{key}
可以引用特定的消息。而根據(jù)不同的語(yǔ)言從與其對(duì)應(yīng)的外部化文本中獲取同一個(gè)key的消息,可以實(shí)現(xiàn)國(guó)際化。
(4)配置國(guó)際化解析器
package com.rtxtitanv.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.LocaleResolver; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.thymeleaf.util.StringUtils; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.Locale; /** * @author rtxtitanv * @version 1.0.0 * @name com.rtxtitanv.config.WebConfig * @description 配置自定義國(guó)際化解析器 * @date 2021/7/6 16:25 */ @Configuration public class WebConfig implements WebMvcConfigurer { @Bean public LocaleResolver localeResolver() { return new MyLocaleResolver(); } /** * 自定義LocaleResolver */ public static class MyLocaleResolver implements LocaleResolver { @Override public Locale resolveLocale(HttpServletRequest request) { // 接收語(yǔ)言參數(shù) String lang = request.getParameter("lang"); // 使用默認(rèn)語(yǔ)言 Locale locale = Locale.getDefault(); // 語(yǔ)言參數(shù)不為空就設(shè)置為該語(yǔ)言 if (!StringUtils.isEmptyOrWhitespace(lang)) { String[] s = lang.split("_"); locale = new Locale(s[0], s[1]); } return locale; } @Override public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {} } }
(5)Controller
@GetMapping(value = {"/index", "/"}) public String index() { return "i18n"; }
(5)測(cè)試
訪問模板,默認(rèn)語(yǔ)言為中文:
點(diǎn)擊英文鏈接切換語(yǔ)言為英文:
點(diǎn)擊中文鏈接切換語(yǔ)言為中文:
11.常用工具類對(duì)象
之前在文中已經(jīng)簡(jiǎn)單地總結(jié)了Thymeleaf中的工具類對(duì)象和它的作用。這里結(jié)合實(shí)例來總結(jié)一下常用工具類對(duì)象具體方法的使用,由于工具類對(duì)象較多,這里就總結(jié)Dates、Numbers和Strings的具體使用方法。至于其他對(duì)象的方法,可以參考官方文檔。
(1)Dates
模板date.html
如下:
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>工具類對(duì)象Dates</title> </head> <body> <div> <span>格式化日期格式1(format):</span> <span th:text="${#dates.format(date)}"></span> <br/> <span>格式化日期格式2(format):</span> <span th:text="${#dates.format(date, 'yyyy/MM/dd hh:mm:ss')}"></span> <br/> <span>獲取年(year):</span> <span th:text="${#dates.year(date)}"></span> <br/> <span>獲取月(month):</span> <span th:text="${#dates.month(date)}"></span> <br/> <span>獲取日(day):</span> <span th:text="${#dates.day(date)}"></span> <br/> <span>獲取時(shí)(hour):</span> <span th:text="${#dates.hour(date)}"></span> <br/> <span>獲取分(minute):</span> <span th:text="${#dates.minute(date)}"></span> <br/> <span>獲取秒(second):</span> <span th:text="${#dates.second(date)}"></span> <br/> <span>獲取毫秒(millisecond):</span> <span th:text="${#dates.millisecond(date)}"></span> <br/> <span>獲取月份名稱(monthName):</span> <span th:text="${#dates.monthName(date)}"></span> <br/> <span>獲取星期索引,1為星期日,2為星期1,···,7為星期六(dayOfWeek):</span> <span th:text="${#dates.dayOfWeek(date)}"></span> <br/> <span>獲取星期名稱(dayOfWeekName):</span> <span th:text="${#dates.dayOfWeekName(date)}"></span> <br/> <span>創(chuàng)建當(dāng)前date和time(createNow):</span> <span th:text="${#dates.createNow()}"></span> <br/> <span>創(chuàng)建當(dāng)前date,time設(shè)置為00:00(createToday):</span> <span th:text="${#dates.createToday()}"></span> </div> </body> </html>
ThymeleafController
中新增以下方法:
@GetMapping("/dates") public String dates(Model model) { model.addAttribute("date", new Date()); return "dates"; }
效果:
(2)Numbers
模板number.html
如下:
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>工具類對(duì)象Numbers</title> </head> <body> <div> <span>整數(shù)格式化 - 設(shè)置最小整數(shù)位數(shù)為3(formatInteger):</span> <span th:text="${#numbers.formatInteger(num, 3)}"></span> <br/> <span>整數(shù)格式化 - 設(shè)置最小整數(shù)位數(shù)為6(formatInteger):</span> <span th:text="${#numbers.formatInteger(num, 6)}"></span> <br/> <span>整數(shù)格式化 - 設(shè)置千位分隔符為.(formatInteger):</span> <span th:text="${#numbers.formatInteger(num, 6, 'POINT')}"></span> <br/> <span>整數(shù)格式化 - 設(shè)置千位分隔符為,(formatInteger):</span> <span th:text="${#numbers.formatInteger(num, 6, 'COMMA')}"></span> <br/> <span>整數(shù)數(shù)組格式化(arrayFormatInteger):</span> <span th:each="element:${#numbers.arrayFormatInteger(nums, 6)}">[[${element}]] </span> <br/> <span>小數(shù)格式化 - 設(shè)置最小整數(shù)位數(shù)為5且精確保留3位小數(shù)位數(shù)(formatDecimal)</span> <span th:text="${#numbers.formatDecimal(num2, 5, 3)}"></span> <br/> <span>小數(shù)格式化 - 設(shè)置千位分隔符為.且小數(shù)點(diǎn)分隔符為,(formatDecimal)</span> <span th:text="${#numbers.formatDecimal(num2, 5, 'POINT', 3, 'COMMA')}"></span> <br/> <span>貨幣格式化(formatCurrency):</span> <span th:text="${#numbers.formatCurrency(num)}"></span> <br/> <span>百分比格式化 - 設(shè)置最小整數(shù)位數(shù)為2且精確保留3位小數(shù)(formatPercent):</span> <span th:text="${#numbers.formatPercent(0.25831694, 2, 3)}"></span> <br/> <span>創(chuàng)建整數(shù)數(shù)字序列 - 序列從1到10步長(zhǎng)為3(sequence):</span> <span th:each="n:${#numbers.sequence(1, 10, 3)}">[[${n}]] </span> <br/> </div> </body> </html>
ThymeleafController
中新增以下方法:
@GetMapping("/numbers") public String numbers(Model model) { Integer[] numArray = {1000, 666, 88888}; model.addAttribute("num", 99999); model.addAttribute("num2", 66.6658932); model.addAttribute("nums", numArray); return "numbers"; }
效果:
(3)Strings
模板strings.html
如下:
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>工具類對(duì)象Strings</title> </head> <body> <div> <span>字符串轉(zhuǎn)換(toString):</span> <span th:text="${#strings.toString(user)}"></span> <br/> <span>檢查字符串是否為空(isEmpty):</span> <span th:text="${#strings.isEmpty(user.username)}"></span> <br/> <span>字符串為空時(shí)使用默認(rèn)值(defaultString):</span> <span th:text="${#strings.defaultString(user.password, 'admin')}"></span> <br/> <span>檢查字符串是否以指定片段開頭(startsWith):</span> <span th:text="${#strings.startsWith(user.username, 'Spring')}"></span> <br/> <span>檢查字符串是否以指定片段結(jié)尾(endsWith):</span> <span th:text="${#strings.endsWith(user.username, 'test')}"></span> <br/> <span>檢查字符串是否包含指定片段(contains):</span> <span th:text="${#strings.contains(user.username, 'Thymeleaf')}"></span> <br/> <span>判斷兩個(gè)字符串是否相等(equals):</span> <span th:text="${#strings.equals(user.username, str)}"></span> <br/> <span>判斷兩個(gè)字符串是否相等,忽略大小寫(equalsIgnoreCase):</span> <span th:text="${#strings.equalsIgnoreCase(user.username, 'springboot-thymeleaf-strings-test')}"></span> <br/> <span>獲取字符串長(zhǎng)度(length):</span> <span th:text="${#strings.length(user.username)}"></span> <br/> <span>字符串轉(zhuǎn)換為大寫字母(toUpperCase):</span> <span th:text="${#strings.toUpperCase(user.username)}"></span> <br/> <span>字符串轉(zhuǎn)換為小寫字母(toLowerCase):</span> <span th:text="${#strings.toLowerCase(user.username)}"></span> <br/> <span>片段在字符串中的索引(indexOf):</span> <span th:text="${#strings.indexOf(user.username, 'Boot')}"></span> <br/> <span>字符串去除空格(trim):</span> <span th:text="${#strings.trim(str)}"></span> <br/> <span>字符串省略(abbreviate):</span> <span th:text="${#strings.abbreviate(user.username, 23)}"></span> <br/> <span>字符串截取,從指定索引開始截取到末尾(substring):</span> <span th:text="${#strings.substring(user.username, 11)}"></span> <br/> <span>字符串截取指定開始索引到結(jié)束索引之間的部分,不包含結(jié)束索引字符(substring):</span> <span th:text="${#strings.substring(user.username, 11, 20)}"></span> <br/> <span>截取指定字符串第一次出現(xiàn)前的字符串(substringBefore):</span> <span th:text="${#strings.substringBefore(user.username, '-')}"></span> <br/> <span>截取指定字符串第一次出現(xiàn)后的字符串(substringAfter):</span> <span th:text="${#strings.substringAfter(user.username, '-')}"></span> <br/> <span>字符串替換(replace):</span> <span th:text="${#strings.replace(user.username, '-', '_')}"></span> <br/> <span>從字符串頭部向前追加(prepend):</span> <span th:text="${#strings.prepend(user.username, '用戶名是')}"></span> <br/> <span>從字符串尾部向后追加(append):</span> <span th:text="${#strings.append(user.username, '是用戶名')}"></span> <br/> <span>字符串連接(concat):</span> <span th:text="${#strings.concat(user.username, '-concat')}"></span> <br/> <span>字符串連接(concatReplaceNulls):</span> <span th:text="${#strings.concatReplaceNulls(user.username, '用戶名是', null, '-concatReplaceNulls')}"></span> <br/> <span>字符串拆分(arraySplit):</span> <span th:each="element:${#strings.arraySplit(user.username, '-')}">[[${element}]] </span> <br/> <span>字符串組合(arrayJoin):</span> <span th:text="${#strings.arrayJoin(strs, '-')}"></span> <br/> <span>隨機(jī)字符串(randomAlphanumeric):</span> <span th:text="${#strings.randomAlphanumeric(16)}"></span> </div> </body> </html>
ThymeleafController
中新增以下方法:
@GetMapping("/strings") public String strings(Model model) { model.addAttribute("user", new User(1L, "SpringBoot-Thymeleaf-Strings-Test", "")); model.addAttribute("str", "SpringBoot Thymeleaf Strings Test"); model.addAttribute("strs", new String[] {"SpringBoot", "Thymeleaf", "Strings", "Test"}); return "strings"; }
效果:
代碼示例
Github:https://github.com/RtxTitanV/springboot-learning/tree/master/springboot2.x-learning/springboot-thymeleaf
到此這篇關(guān)于SpringBoot2.x 集成 Thymeleaf的文章就介紹到這了,更多相關(guān)SpringBoot2.x 集成 Thymeleaf內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- 淺析SpringBoot中使用thymeleaf找不到.HTML文件的原因
- SpringBoot引入Thymeleaf的實(shí)現(xiàn)方法
- springboot如何使用thymeleaf模板訪問html頁(yè)面
- IDEA+maven+SpringBoot+JPA+Thymeleaf實(shí)現(xiàn)Crud及分頁(yè)
- springboot用thymeleaf模板的paginate分頁(yè)完整代碼
- Springboot Thymeleaf數(shù)據(jù)迭代實(shí)現(xiàn)過程
- Springboot Thymeleaf實(shí)現(xiàn)HTML屬性設(shè)置
相關(guān)文章
通過FeignClient調(diào)用微服務(wù)提供的分頁(yè)對(duì)象IPage報(bào)錯(cuò)的解決
這篇文章主要介紹了通過FeignClient調(diào)用微服務(wù)提供的分頁(yè)對(duì)象IPage報(bào)錯(cuò)的解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-03-03SpringBoot Redis配置多數(shù)據(jù)源的項(xiàng)目實(shí)踐
springboot中默認(rèn)的redis配置是只能對(duì)單個(gè)redis庫(kù)進(jìn)行操作的, 那么我們需要多個(gè)庫(kù)操作的時(shí)候這個(gè)時(shí)候就可以采用redis多數(shù)據(jù)源 ,本文就介紹了SpringBoot Redis配置多數(shù)據(jù)源,感興趣的可以了解一下2023-07-07一文詳解Java中的反射與new創(chuàng)建對(duì)象
Java中的反射(Reflection)和使用new關(guān)鍵字創(chuàng)建對(duì)象是兩種不同的對(duì)象創(chuàng)建方式,各有優(yōu)缺點(diǎn)和適用場(chǎng)景,本文小編給大家詳細(xì)介紹了Java中的反射與new創(chuàng)建對(duì)象,感興趣的小伙伴跟著小編一起來看看吧2024-07-07Mybatis-Plus實(shí)現(xiàn)多主鍵批量保存及更新詳情
這篇文章主要介紹了Mybatis-Plus實(shí)現(xiàn)多主鍵批量保存及更新詳情,文章通過圍繞主題展開詳細(xì)的內(nèi)容介紹,具有一定的參考價(jià)值,需要的小伙伴可以參考一下2022-09-09使用SpringMVC訪問Controller接口返回400BadRequest
這篇文章主要介紹了使用SpringMVC訪問Controller接口返回400BadRequest,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-03-03Jmeter接口登錄獲取參數(shù)token報(bào)錯(cuò)問題解決方案
這篇文章主要介紹了Jmeter接口登錄獲取參數(shù)token報(bào)錯(cuò)問題解決方案,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-07-07Java Swing程序設(shè)計(jì)實(shí)戰(zhàn)
今天教大家怎么用JavaSwing工具包實(shí)現(xiàn)一個(gè)程序的界面設(shè)計(jì),文中有非常詳細(xì)的代碼示例及注釋,對(duì)正在學(xué)習(xí)Java的小伙伴們很有幫助,需要的朋友可以參考下2021-05-05