1.thymeleaf介紹
Thymeleaf 官網:www.thymeleaf.org,可下載操作手冊
Thymeleaf 可以在有網絡和無網絡的環境下皆可運行,即它可以讓美工在瀏覽器查看靜態效果,也可以讓程序員在服務器查看帶 數據的動態頁面效果
html模板引擎,它可以完全替代 JSP,提供spring標準方言和一個與 SpringMVC 完美集成的可選模塊,可以快速的實現表單綁定、屬性編輯器、國際化等功能
2.在application.properties中,進行如下配置
springboot封裝的thymeleaf默認是2.x版本,如果想使用最新的3.x版本可以在< properties >中配置版本
3.
下面詳細分享一些常用用法:
請提前在項目resources目錄下創建css、js文件夾,分別創建index.css,common.js文件,並在js文件夾下放入jquery.min.js,後面的html和模版需要用到
編號 | 屬性 | 描述 | 示例 |
1 | th:text | 計算其值表達式並將結果設置爲標籤的標籤體 | <p th:text="${userName}">中國</p>,值爲 null 爲空時,整個標籤不顯示任何內容。 |
2 | th:utext | th:text 會對結果中的特殊字符轉義,th:utext 不會轉義,適合後端直接向前端輸出 html 標籤的內容 | <p th:utext="${userInfo}">中國</p>,,userInfo可以是html內容。 |
3 | th:attr | 爲標籤中的任意屬性設置,可以一次設置多個屬性 | <a href="" th:attr="title='前往百度',href='http://baidu.com'">前往百度</a> |
4 | th:* | 爲 html 指定的屬性設值,一次設置一個 | <a href="" th:title='前往百度' th:href="'http://baidu.com'">前往百度</a> |
5 | th:alt-title | 同時爲 alt 與 title 屬性賦值 | <a href="#" th:alt-title="'th:A-B'">th:A-B</a> |
6 | th:lang-xmllang | 同時爲 lang 、xmllang 屬性賦值 | <head lang="en" th:lang-xmllang="en"> |
7 | th:fragment | 定義模板片段 | <div th:fragment="copy"> |
8 | th:insert | 將被引用的模板片段插⼊到自己的標籤體中 | <div th:insert="~{footer :: copy}"></div> |
9 | th:replace | 將被引用的模板片段替換掉自己 | <div th:replace="footer :: copy"></div> |
10 | th:include | 類似於 th:insert,⽽不是插⼊⽚段,它只插⼊此⽚段的內容 | <div th:include="footer :: copy"></div> |
11 | th:remove | 刪除模板中的某些代碼片段 | <tr th:remove="all">... |
12 | th:each | 迭代數據,如 數組、List、Map 等 | <tr th:each="user : ${userList}">... |
13 | th:if | 條件爲 true 時,顯示模板⽚段,否則不顯示 | <p th:if="${isMarry}">已婚1</p> |
14 | 條件爲 false 時,顯示模板⽚段,否則不顯示 | <p th:unless="!${isMarry}">已婚2</p> |
|
15 | 與 Java 中的 switch 語句等效,有條件地顯示匹配的內容 | <div th:switch="1"> | |
16 | th:case | 配合 th:switch 使用 | <div th:switch="1"> <p th:case="0">管理員</p> <p th:case="1">操作員</p> <p th:case="*">未知用戶</p> </div> |
17 | th:with | 定義局部變量 | <div th:with="userFirst=${userList[0]}"> |
18 | 禁用內聯表達式,內聯js,內聯css | <script type="text/javascript" th:inline="javascript"> | |
(1)使用模版:定義公用頭部css和尾部js引用,在其他頁面中引用模版,更換樣式時,只需更換模版中的引用即可
操作步驟:在resources—templates目錄下創建一個template的文件夾,裏面創建common.html文件,文件內容如下,以下有兩種用法:
在需要引用頭部、尾部的html文件中,使用 th:replace=“template/common :: header” 模版路徑 :: 模版名稱
(2)變量表達式: Spring EL表達式(在Spring術語中也叫model attributes)。如下所示
直接 . 出後臺返回對象屬性 <span th:text="${user.name}">
直接循環出後臺返回數組-list屬性 <ul><li th:each="user: ${users}" th:text="${user.name}"></li></ul>
可以寫th:if 判斷, <div th:if="${user.age} > 20">我大於20啦</div>
th:unless與 if 相反 <div th:unless="${user.age} > 20">我還年輕</div>
5.貼下我的代碼和運行效果,項目中常用的就這些
效果如下: