前言
操作前建議先參考我的另一篇博客:玩轉 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
用於文本內容的顯示操作。
- th:text 進行文本替換 不會解析html
- 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&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">
© 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" >
© 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">
© 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>3</p></div>
<div><p>4</p></div>
模板代碼:
<div th:each="num : ${#numbers.sequence(0,4,1)}" >
<p th:text="${num}"></p>
</div>
結果頁面:
<div><p>0</p></div>
<div><p>1</p></div>
<div><p>2</p></div>
<div><p>3</p></div>
<div><p>4</p></div>
模板代碼:
<div th:each="num : ${#numbers.sequence(0,10,2)}" >
<p th:text="${num}"></p>
</div>
結果頁面:
<div><p>0</p></div>
<div><p>2</p></div>
<div><p>4</p></div>
#strings
處理String的相關操作,包括:
- 字符串轉換(toString)
- 檢查字符串是否為空(isEmpty)
- 字符串是為空替換操作(defaultString)
- 檢查字符串中是否包含某個字符串(contains containsIgnoreCase)
- 檢查字符串是以片段開頭還是結尾(startsWith endsWith)
- 截取(substring substringAfter)
- 替換(replace)
- 追加(prepend append)
- 變更大小寫(toUpperCase toLowerCase)
- 拆分和組合字符串(arrayJoin arraySplit)
- 去空格(trim)
- 縮寫文本(abbreviate)
- 字符串連接(concat)
代碼演示:
java 代碼
@RequestMapping("/strings")
public String strings(Model model){
Object object = "123";
model.addAttribute("object",object);
List<Integer> numList = new ArrayList<Integer>();
numList.add(1);
numList.add(12);
numList.add(13);
model.addAttribute("numList",numList);
}
Java代碼
Object object = "123";
模板代碼:
<p th:text="${object}"></p>
結果頁面:
<p>123</p>
toString操作
Java代碼
Object object = "123";
模板代碼:
<p th:text="${#strings.toString(object)}"></p>
結果頁面:
<p>123</p>
Java代碼
List<Integer> numList = new ArrayList<Integer>();
numList.add(1);
numList.add(12);
numList.add(13);
模板代碼:
<p th:text="${#strings.toString(numList)}"></p>
結果頁面:
<p>[1, 12, 13]</p>
isEmpty操作
Java代碼
String name = null;
模板代碼:
<p th:text="${#strings.isEmpty(name)}"></p>
結果頁面:
<p>true</p>
Java代碼
List<String> nameList = new ArrayList<String>();
nameList.add("1");
nameList.add(null);
模板代碼:
<p th:text="${#strings.listIsEmpty(nameList)}"></p>
結果頁面:
<p>[false, true]</p>
Java代碼
Set<String> nameSet = new HashSet<String>();
nameSet.add(null);
nameSet.add("1");
模板代碼:
<p th:text="${#strings.setIsEmpty(nameSet)}"></p>
結果頁面:
<p>[true, false]</p>
defaultString操作
Java代碼
String name = null;
模板代碼:
<p th:text="${#strings.defaultString(text,'該值為null')}"></p>
結果頁面:
<p>該值為null</p>
Java代碼
List<String> nameList = new ArrayList<String>();
nameList.add("1");
nameList.add(null);
模板代碼:
<p th:text="${#strings.listDefaultString(textList,'該值為null')}"></p>
結果頁面:
<p>[abc, 該值為null]</p>
contains操作
模板代碼:
<p th:text="${#strings.contains('abcez','ez')}"></p>
結果頁面:
<p>true</p>
模板代碼:
<p th:text="${#strings.containsIgnoreCase('abcEZ','ez')}"></p>
結果頁面:
<p>true</p>
startsWith endsWith 操作
模板代碼:
<p th:text="${#strings.startsWith('Donabcez','Don')}"></p>
結果頁面:
<p>true</p>
模板代碼:
<p th:text="${#strings.endsWith('Donabcezn','n')}"></p>
結果頁面:
<p>true</p>
indexOf操作
模板代碼:
<p th:text="${#strings.indexOf('abcefg','e')}"></p>
結果頁面:
<p>3</p>
substring操作
模板代碼:
<p th:text="${#strings.substring('abcefg',3,5)}"></p>
結果頁面:
<p>ef</p>
replace操作
模板代碼:
<p th:text="${#strings.replace('lasabce','las','ler')}"></p>
結果頁面:
<p>lerabce</p>
prepend操作
模板代碼:
<p th:text="${#strings.prepend('abc','012')}"></p>
結果頁面:
<p>012abc</p>
append操作
模板代碼:
<p th:text="${#strings.append('abc','456')}"></p>
結果頁面:
<p>abc456</p>
toUpperCase操作
模板代碼:
<p th:text="${#strings.toUpperCase('abc')}"></p>
結果頁面:
<p>ABC</p>
toLowerCase操作
模板代碼:
<p th:text="${#strings.toLowerCase('ABC')}"></p>
結果頁面:
<p>abc</p>
length操作
模板代碼:
<p th:text="${#strings.length('abc')}"></p>
結果頁面:
<p>3</p>
trim操作
模板代碼:
<p th:text="${#strings.trim(' abc ')}"></p>
結果頁面:
<p>abc</p>
abbreviate操作
模板代碼:
<p th:text="${#strings.abbreviate('12345678910',10)}"></p>
結果頁面:
<p>1234567...</p>
#objects
處理Object對象的操作 包含obj不為空返回改值如果為空返回默認值(nullSafe)
java代碼
@RequestMapping("/objects")
public String objects(Model model){
Object obj = null;
model.addAttribute("obj",obj);
}
模板代碼:
<p th:text="${#objects.nullSafe(obj,'該對象為null')}"></p>
結果頁面:
<p>該對象為null</p>
#bools
判斷對象是否為ture或者是否為false的操作。
- 數字 1 為 ture , 0 為 false;
- "on" 為 true, "off" 為false;
- "true" 為true, "false"為 false;
isTrue操作
模板代碼:
<p th:text="${#bools.isTrue(true)} "></p>
結果頁面:
<p>true</p>
模板代碼:
<p th:text="${#bools.isTrue(false)} "></p>
結果頁面:
<p>false</p>
模板代碼:
<p th:text="${#bools.isTrue('on')} "></p>
結果頁面:
<p>true</p>
模板代碼:
<p th:text="${#bools.isTrue('off')} "></p>
結果頁面:
<p>false</p>
模板代碼:
<p th:text="${#bools.isTrue('true')} "></p>
結果頁面:
<p>true</p>
模板代碼:
<p th:text="${#bools.isTrue('false')} "></p>
結果頁面:
<p>false</p>
模板代碼:
<p th:text="${#bools.isTrue(1)} "></p>
結果頁面:
<p>true</p>
模板代碼:
<p th:text="${#bools.isTrue(0)} "></p>
結果頁面:
<p>false</p>
#arrays
處理數組的相關操作的內置對象,包含:
- 轉換數組 toStringArray toIntegerArray,
- 獲取數組的長度(length ),
- 判斷數組是否為空(isEmpty )
- 是否包含某個元素(contains)
- 是否包含一批元素(containsAll)
其中 toStringArray 等操作接受的是Object對象,containsAll 接受一批元素支持數組和集合的參數。
toStringArray操作
java代碼
@RequestMapping("/arrays")
public String arrays(Model model){
List<String> object = new ArrayList<String>();
object.add("1");
object.add("2");
model.addAttribute("object",object);
}
模板代碼:
<p th:text="${#arrays.toStringArray(object)} "></p>
結果頁面:
<p>[Ljava.lang.String;@3cca655d</p>
length操作
java代碼
Integer[] array = {1,2,3};
模板代碼:
<p th:text="${#arrays.length(array)} "></p>
結果頁面:
<p>3</p>
isEmpty操作
java代碼
Integer[] array = {1,2,3};
模板代碼:
<p th:text="${#arrays.isEmpty(array)} "></p>
結果頁面:
<p>false</p>
contains操作
java代碼
Integer[] array = {1,2,3};
模板代碼:
<p th:text="${#arrays.contains(array,1)} "></p>
結果頁面:
<p>true</p>
containsAll操作
java代碼
Integer[] array = {1,2,3};
Integer[] array2 = {1,3};
模板代碼:
<p th:text="${#arrays.containsAll(array,array2)} "></p>
結果頁面:
<p>true</p>
#lists
處理 list 相關操作的內置對象,包括:
- 計算長度(size)
- 檢查list是否為空(isEmpty)
- 檢查元素是否包含在list中(contains,containsAll)
- 對給定list的副本排序(sort)
java代碼
@RequestMapping("/lists")
public String lists(Model model){
List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(3);
list.add(2);
model.addAttribute("list",list);
}
模板代碼:
<p th:text="${#lists.size(list)} "></p>
結果頁面:
<p>3</p>
java代碼:
List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(3);
list.add(2);
模板代碼:
<p th:text="${#lists.isEmpty(list)} "></p>
結果頁面:
<p>false</p>
java代碼:
List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(3);
list.add(2);
模板代碼:
<p th:text="${#lists.contains(list, 1)}"></p>
結果頁面:
<p>true</p>
java代碼:
List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(3);
list.add(2);
List<Integer> list2 = new ArrayList<Integer>();
list2.add(1);
list2.add(2);
模板代碼:
<!-- elements 可以是數組 集合 list -->
<p th:text="${#lists.containsAll(list,list2)}"></p>
結果頁面:
<p>true</p>
java代碼:
List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(3);
list.add(2);
模板代碼:
<p th:text="${#lists.sort(list)}"></p>
結果頁面:
<p>[1, 2, 3]</p>
#sets
處理 set 相關操作的內置對象,包括:
- 轉換為Set(toSet)
- 計算長度(size)
- 檢查set是否為空(isEmpty)
- 檢查元素是否包含在set中 (contains,containsAll)
size操作
java代碼
@RequestMapping("/sets")
public String sets(Model model){
Set<Integer> set = new HashSet<Integer>();
set.add(1);
set.add(2);
set.add(3);
set.add(4);
model.addAttribute("set",set);
}
模板代碼:
<p th:text="${#sets.size(set)} "></p>
結果頁面:
<p>3</p>
isEmpty 操作
java代碼:
Set<Integer> set = new HashSet<Integer>();
set.add(1);
set.add(2);
set.add(3);
set.add(4);
模板代碼:
<p th:text="${#sets.isEmpty(set)} "></p>
結果頁面:
<p>false</p>
contains操作
java代碼:
Set<Integer> set = new HashSet<Integer>();
set.add(1);
set.add(2);
set.add(3);
set.add(4);
模板代碼:
<p th:text="${#sets.contains(set, 1)}"></p>
結果頁面:
<p>true</p>
containsAll操作
java代碼
Set<Integer> set = new HashSet<Integer>();
set.add(1);
set.add(2);
set.add(3);
set.add(4);
Integer[] elements = {1,2};
model.addAttribute("elements",elements);
模板代碼:
<p th:text="${#sets.containsAll(set, elements)}"></p>
結果頁面:
<p>true</p>
sort操作
java代碼:
Set<Integer> set = new HashSet<Integer>();
set.add(1);
set.add(2);
set.add(3);
set.add(4);
模板代碼:
<p th:text="${#lists.sort(list)}"></p>
結果頁面:
<p>[1, 2, 3]</p>
#maps
處理 map相關操作的內置對象,包括:
- 計算長度(size)
- 檢查map是否為空(isEmpty)
- 檢查映射中是否包含鍵或值(containsKey,containsAllKeys,containsValue)
java代碼:
@RequestMapping("/maps")
public String maps(Model model){
Map<String,Integer> map = new HashMap<String,Integer>();
map.put("1",1);
map.put("2",2);
map.put("3",3);
model.addAttribute("map",map);
}
模板代碼:
<p th:text="${#maps.size(map)} "></p>
結果頁面:
<p>3</p>
java代碼:
Map<String,Integer> map = new HashMap<String,Integer>();
map.put("1",1);
map.put("2",2);
map.put("3",3);
模板代碼:
<p th:text="${#maps.isEmpty(map)} "></p>
結果頁面:
<p>false</p>
java代碼:
Map<String,Integer> map = new HashMap<String,Integer>();
map.put("1",1);
map.put("2",2);
map.put("3",3);
模板代碼:
<p th:text="${#maps.containsKey(map, '1')}"></p>
結果頁面:
<p>true</p>
java代碼:
Map<String,Integer> map = new HashMap<String,Integer>();
map.put("1",1);
map.put("2",2);
map.put("3",3);
String[] keys = {"1","2"};
model.addAttribute("keys",keys);
模板代碼:
<!-- keys 可以是數組可以是集合 -->
<p th:text="${#maps.containsAllKeys(map, keys)}"></p>
結果頁面:
<p>true</p>
java代碼:
Map<String,Integer> map = new HashMap<String,Integer>();
map.put("1",1);
map.put("2",2);
map.put("3",3);
模板代碼:
<p th:text="${#maps.containsValue(map, 2)}"></p>
結果頁面:
<p>true</p>
java代碼:
Map<String,Integer> map = new HashMap<String,Integer>();
map.put("1",1);
map.put("2",2);
map.put("3",3);
Integer[] values = {1,2};
model.addAttribute("values",values);
模板代碼:
<!-- values 可以是數組可以是集合 -->
<p th:text="${#maps.containsAllValues(map, values)}"></p>
結果頁面:
<p>true</p>
#aggregates
用戶處理集合或者數組的一些統計操作,包括:
- 求和(sum)
- 求平均值(avg)
- 處理包裝類型或基本類型的數組或集合
求和操作
java代碼:
@RequestMapping("/aggregates")
public String aggregates(Model model){
Integer[] array = {1,2,3,4};
model.addAttribute("array",array);
return "/course/aggregates";
}
模板代碼:
<p th:text="${#aggregates.sum(array)} "></p>
結果頁面:
<p>10</p>
java代碼:
List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(2);
list.add(3);
list.add(4);
模板代碼:
<p th:text="${#aggregates.sum(list)} "></p>
結果頁面:
<p>10</p>
求平均值操作
java代碼:
Integer[] array = {1,2,3,4};
模板代碼:
<p th:text="${#aggregates.avg(array)} "></p>
結果頁面:
<p>2.5</p>
java代碼:
List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(2);
list.add(3);
list.add(4);
模板代碼:
<p th:text="${#aggregates.avg(list)} "></p>
結果頁面:
<p>2.5</p>
小結
本文主要介紹 Thymeleaf 的基礎用法、內聯、模板布局、預定義的工具對象。整體來看Thymeleaf 使用語法還是很強大的,但是我這里不會強烈安利你使用 Thymeleaf,正如 Thymeleaf 官方所說:“無論如何,比較技術的最好方法是自己使用它們,並感覺哪個最適合你!” 你同樣可以選擇使用 Velocity 或 FreeMarker。
代碼示例
具體代碼示例請查看我的GitHub 倉庫 springbootexamples 中的 spring-boot-2.x-thymeleaf 下的 course 包下查看。
GitHub:https://github.com/zhuoqianmingyue/springbootexamples
參考文獻:
https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html