1.什么是Thymeleaf
??Spring Boot 主要支持Thymeleaf、Freenrtarker、Mustache、Groovy Templates 等模板引擎,
??Thymeleaf語法并不會破壞檔案的結構,所以Thymeleaf模板依然是有效的HTML檔案,模 板還可以被用作作業原型,Thymeleaf會在運行期內替換掉靜態值,它的模板檔案能直接在瀏覽器 中打開并正確顯示頁面,而不需要啟動整個Web應用程式,
1.1 為什么需要模板引擎
??Thymeleaf解決了前端開發人員要和后端開發人員配置一樣環境的尷尬和低效,它通過屬性進 行模板渲染,不需要引入不能被瀏覽器識別的新的標簽,頁面直接作為HTML檔案,用瀏覽器打開頁面即可看到最終的效果,可以降低前后端人員的溝通成本,
1.2 使用Thymeleaf
要使用Thymeleaf,首先需要引入依賴,直接在pom.xml檔案中加入以下依賴即可,
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
<version>2.0.7.RELEASE</version>
</dependency>
在模板檔案中加入決議,在html檔案中加入命名空間即可,
<html lang="en" xmlns:th="http://www.thymeleaf.org/">
1.3 配置視圖決議器
??Spring Boot默認的頁面映射路徑(即模板檔案存放的位置)為 "classpath: /templates/*.html" , 靜態檔案路徑為 "classpath:/static/",其中可以存放層疊樣式表CSS( Cascading Style Sheets )、 JS (JavaScript)等模板共用的靜態檔案,在application.yml檔案中,可以配置Thymeleaf模板決議器屬性
spring:
thymeleaf:
mode: HTML5
encoding: UTF-8
servlet:
content-type: text/html
cache: false
spring.thymeleaf.mode:代表 Thymeleaf 模式,
spring.thymeleaf.encodmg:代表 Thymeleaf 編碼格式,
thymeleaf.content-type:代表檔案型別,
thymeleaf.cache:代表是否啟用 Thymeleaf 的快取,
2.基礎用法
2.1 參考命名空間
??要使用Thymeleaf,則需要先要加入依賴,然后在模板檔案中參考命名空間,如下:
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
??之后,會進行Thymeleaf模板標簽的渲染,如果用Spring Security作為安全認證,且需要顯示登錄用戶的資訊,則可以先在視圖中加入額外的thymeleaf-extras-springsecurity依賴
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity3</artifactId>
<version>2.1.0.RELEASE</version>
</dependency>
??然后 在模板檔案中加入thymeleaf-extras-springsecurity命名空間,具體見以下代碼:
<html lang="en"
xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/tyemeleaf-extras-springsecurity5">
<span sec:authorization="name"></span>
<span sec:authorize="hasRole('ROLE_ADMIN')">管理員</span>
<span sec:authorize="hasRole('ROLE_USER')">普通用戶</span>
這里特別要注意查看 spring-boot—starter-thymeleaf 依賴和 thymeleaf-extras- springsecurity依賴的版本是否兼容,如果不兼容,則無法呼叫登錄用戶的資訊,
2.2 常用th標簽
(1)th:text
<div th:text="${name}">name</div>
它用于顯示控制器傳入的name值,
如果name不存在,要顯示默認值,則使用以下代碼:
<span th:text="${ame} ?:'默認值'"></span>
(2)th:object
它用于接收后臺傳過來的物件,如以下代碼:
th:object="${user}"
(3)th:action
它用來指定表單提交地址,
<form th:action="@{/article/}+${article.id}" method="post"></form>
(4)th:value
它用物件將id的值替換為value的屬性,
<input type="text" th:value="https://www.cnblogs.com/liwenruo/p/${article.id}" name="id"/>
(5)th:field
它用來系結后臺物件和表單資料,Thymeleaf里的"th:field"等同于"th:name"和"th: valued"其具體使用方法見以下代碼:
<input type="text" id="title" name="title" th:field="${book.id}"/><input type="text" name="title" th:field="${fields}"/>
2.3 Thymeleaf 中的 URL 寫法
Thymeleaf是通過語法@{…}來處理URL的,需要使用"th:href"和"th:src"等屬性,如以下代碼
<a th:href="https://www.cnblogs.com/liwenruo/p/@{http://www.thymeleaf.org}">絕對路徑</a>
<a th:href="https://www.cnblogs.com/liwenruo/p/@{/}">相對路徑</a>
<a th:href="https://www.cnblogs.com/liwenruo/p/@{css/bootstrap.min.css}">默認訪問static下的css檔案夾</a>
2.4用Thymeleaf進行條件求值
Thymeleaf通過 "th:if" 和 "th:unless" 屬性迸行條件判斷,在下面的例子中,<a>標簽只有 在 "th:if" 中的條件成立時才顯示,
<a th:href="https://www.cnblogs.com/liwenruo/p/@{/login}" th:if="${session.user == null}">Login</a>
"th:unless" 與 "th:if" 恰好相反,只有當運算式中的條件不成立時才顯示其內容,在下方代碼中,如果用戶session為空,則不顯示登錄(login )鏈接,
<a th:href="https://www.cnblogs.com/liwenruo/p/@{/login}" th:unless="${session.user == null}">Login</a>
2.5 Switch
<div th:switch="${book.getId()}">
<p th:case="ADMIN">管理員</p>
<p th:case="VIP">vip會員</p>
<p th:case="*">普通會員</p>
</div>
上述代碼的意思是:如果用戶角色(role)是admin,則顯示“管理員”;如果用戶角色是vip, 則顯示"vip會員”;如果都不是,則顯示“普通會員”,即使用“*”表示默認情況,
2.6 Thymeleaf中的字串替換
有時需要對文字中的某一處地方進行替換,可以通過字串拼接操作完成,如以下代碼:
<span th:text="'歡迎,'+${book.getUsername()}+'!'"></span>
或者:
<span th:text="|歡迎,${book.getUsername()}!|"></span>
上面的第2種形式限制比較多,|...|中只能包含變數運算式${...},不能包含其他常量、條件運算式等,
2.7 Thymeleaf的運算子
1.算數運算子,
????如果要在模板中進行算數運算,則可以用下面的寫法,以下代碼表示求加和取余運算,
??<span th:text="1+3"></span>??<span th:text="9*3"></span>
2.條件運算子
????下方代碼演示了 if判斷,表示:如果從控制器傳來的role值等于“admin”,則顯示 "歡迎您, 管理員";如果role值等于 "vip",則顯示 "歡迎您,vip會員"
<div th:if="${book.getUsername()} eq admin">
<span>歡迎您,管理員</span>
</div>
<div th:if="${book.getUsername()} eq vip">
<span>歡迎您,vip</span>
</div>
eq是判斷運算式,代表等于,其他的判斷運算式如下,
gt:大于,
ge:大于或等于,
eq:等于,
It:小于,
?? le:小于或等于,
ne:不等于,
3.判斷空值
可以使用if來判斷值是否為空,如以下代碼:
<span th:if="${book.getUsername()}==null">不為空</span>
?<span th:if="${book.getUsername()}!=null">為空</span>
2.8 Thymeleaf公用物件
Thymeleaf還提供了一系列公用(utility)物件,可以通過"#"直接訪問,如以下用法
格式化時間:
<td th:text="${#dates.format(data,'yyyy-MM-dd HH:mm:ss')}">格式化時間</td>
判斷是不是空字串:
<span th:if="${#strings.isEmpty(data)}">空</span>
是否包含(分大小寫):
<span th:if="${#strings.contains(book.getUsername(),'admin')}">包含</span>
3. 處理回圈遍歷
3.1 遍歷物件(object)
在開發程序中,經常會遇到遍歷物件的情況,可以通過 th:each="Object:$(Objects}" 標簽來處理,以下代碼是遍歷從控制器中傳來的書籍物件,
<div th:each="book:${book}">
<li th:text="${book.getUsername()}">姓名</li>
<li th:text="${book.getPassword()}">密碼</li>
</div>
3.2 遍歷分頁(page)
分頁也是極為常見的開發需求,在Thymeleaf中,可以通過 th:each="item : ${page.content}" 標簽來處理page物件,如以下代碼
<div th:each="item:${page.content}">
<li th:text="${item.id}">id</li>
<li th:text="${item.title}">title</li>
</div>
3.3 遍歷串列(list)
要處理list,也使用 th:each="item:${list}"標簽來實作,
<div th:each="item:${list}">
<li th:text="${item.username}">id</li>
<li th:text="${item.password}">title</li>
</div>
3.4 遍歷陣列(array)
使用 th:each="item:${arrays}"標簽來遍歷陣列,如以下代碼:
<div th:each="ArrayList:${ArrayList}">
<li th:text="${ArrayList}">id</li>
</div>
3.5 遍歷集合(map)
集合通過 th:text="${item.key}"顯示集合的 key,通過 th:text="${item.value}" 顯示集合的值,如以下代碼:
<div th:each="map:${map}">
<li th:text="${map.key}"></li>
<li th:text="${map.value}"></li>
</div>
4. 處理公共代碼塊
??一個網頁的結構基本可以分為上(header )、中(body )、下(footer)三個部分,在一般情況 下,header和footer的資訊在各個頁面都會重復顯示,如果每個頁面都復制一份代碼則太麻煩了,設計Thymeleaf的團隊也考慮到代碼復用的問題,提供了 "th:fragment" "th:include" 和 "th:replace"標簽用來處理重復的代碼塊,具體用法如下,
4.1 用fragment標記重復代碼塊
可以通過"th:fragment="header" 標簽來標記重復代碼塊,如以下代碼
<div id="header" th:fragment="header">
公共header
</div>
<div id="footer" th:fragment="footer">
公共footer
</div>
4.2 呼叫重復代碼塊
在需要呼叫的地方,用"th:include"或"th:replace"標簽根據fragment值來呼叫,如以下代碼:
其中~{html檔案名:: 通過fragment起的別名}
<div th:replace="~{test :: header}"></div>
<div th:include="~{test :: footer}"></div>
"th:include"和 "th:replace" 標簽都可以呼叫公共代碼,它們的區別如下,
- th:replace:替換當前標簽為模板中的標簽,比如上面用replace標簽,則代碼替換為:
<div >
??公共header
</div>
- th:include:只加載模板的內容,比如上面用include標簽,則代碼替換為:
<div>
??公共footer
</div>
5. 處理分頁
在MVC開發程序中,分頁也是常用的功能,Thymeleaf可以處理由控制器傳入的分頁引數,
1.用控制器傳入page物件
Pageable pageable = PageRequest.of(start,limit,sort);
Page<Book> page = articleRepository.findAll(pageable);
ModelAndView modelAndView = new ModelAndView("/index");
modelAndView.addObject("page",page);
return modelAndView;
2.用Thymeleaf接收page物件并處理
<div>
<a th:href="https://www.cnblogs.com/liwenruo/p/@{/test(start=0)}">[首頁]</a>
<a th:if="${not page.isFirst()}" th:href="https://www.cnblogs.com/liwenruo/p/@{/test(start=${page.number-1})}">[上頁]</a>
<a th:if="${not page.isLast()}" th:href="https://www.cnblogs.com/liwenruo/p/@{/test(start=${page.number+1})}">[上頁]</a>
<a th:href="https://www.cnblogs.com/liwenruo/p/@{/test(start=${page.totalPages-1})}">[末頁]</a>
</div>
6. 驗證和提示錯誤訊息
大多數表單資訊都需要逬行字串的驗證,以及提供錯誤訊息反饋,Thymeleaf提供了幾種提示錯誤資訊的方法,
6.1欄位錯誤資訊提示
<div>
<span>email:</span>
<span><input type="text" th:field="*{email}" /></span>
<span th:if="${#fields.hasErrors('email')}" th:errors="*{email}">郵箱錯誤</span>
</div>
6.2 提示所有錯誤
<ul>
<li th:each="err:${#fields.errors('*')}" th:text="*{err}">郵箱錯誤</li>
</ul>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/499537.html
標籤:Html/Css
下一篇:web 前端 基礎HTML知識點
