thymeleaf是springboot官方推薦使用的java模板引擎,在springboot的參考指南里的第28.1.10 Template Engines中介紹并推薦使用thymeleaf,建議我們應(yīng)該避免使用jsp,jsp的本質(zhì)是一個(gè)java的servlet類(lèi),jsp引擎將jsp的內(nèi)容編譯成.class,"out.write"輸出到response再響應(yīng)到瀏覽器,雖然java是一次編譯,到處運(yùn)行,但也大大增加了服務(wù)器壓力,而且jsp將后臺(tái)java語(yǔ)言嵌入頁(yè)面,還要放入服務(wù)容器才能打開(kāi),前后端不分離,嚴(yán)重增加了前端工程師的開(kāi)發(fā)工作、效率。
thymeleaf官網(wǎng)對(duì)thymeleaf的介紹:
Thymeleaf is a modern server-side Java template engine for both web and standalone environments.
Thymeleaf's main goal is to bring elegant natural templates to your development workflow — HTML that can be correctly displayed in browsers and also work as static prototypes, allowing for stronger collaboration in development teams.
With modules for Spring Framework, a host of integrations with your favourite tools, and the ability to plug in your own functionality, Thymeleaf is ideal for modern-day HTML5 JVM web development — although there is much more it can do.
thymeleaf使用教程,騷操作:鼠標(biāo)右鍵,翻譯成簡(jiǎn)體中文再看。
thymeleaf使用th屬性賦予每個(gè)標(biāo)簽與后臺(tái)交互的能力,當(dāng)html文件在本地直接用瀏覽器打開(kāi),瀏覽器引擎會(huì)忽略掉th屬性,并正常渲染頁(yè)面,當(dāng)把html文件放到服務(wù)容器訪問(wèn),th屬性與后臺(tái)交互,獲取數(shù)據(jù)替換原先的內(nèi)容,這樣前端工程師在編寫(xiě)html頁(yè)面時(shí),在本地開(kāi)發(fā),正常實(shí)現(xiàn)頁(yè)面邏輯效果即可,數(shù)據(jù)先寫(xiě)死,當(dāng)放到服務(wù)容器時(shí)數(shù)據(jù)從后臺(tái)獲取。
spring對(duì)thymeleaf的配置,來(lái)自springboot參考手冊(cè),Common application properties:https://docs.spring.io/spring-boot/docs/2.1.0.RELEASE/reference/htmlsingle/#common-application-properties
# THYMELEAF (ThymeleafAutoConfiguration)
spring.thymeleaf.cache=true # Whether to enable template caching.
spring.thymeleaf.check-template=true # Whether to check that the template exists before rendering it.
spring.thymeleaf.check-template-location=true # Whether to check that the templates location exists.
spring.thymeleaf.enabled=true # Whether to enable Thymeleaf view resolution for Web frameworks.
spring.thymeleaf.enable-spring-el-compiler=false # Enable the SpringEL compiler in SpringEL expressions.
spring.thymeleaf.encoding=UTF-8 # Template files encoding.
spring.thymeleaf.excluded-view-names=# Comma-separated list of view names (patterns allowed) that should be excluded from resolution.
spring.thymeleaf.mode=HTML # Template mode to be applied to templates. See also Thymeleaf's TemplateMode enum.
spring.thymeleaf.prefix=classpath:/templates/ # Prefix that gets prepended to view names when building a URL.
spring.thymeleaf.reactive.chunked-mode-view-names=# Comma-separated list of view names (patterns allowed) that should be the only ones executed in CHUNKED mode when a max chunk size is set.
spring.thymeleaf.reactive.full-mode-view-names=# Comma-separated list of view names (patterns allowed) that should be executed in FULL mode even if a max chunk size is set.
spring.thymeleaf.reactive.max-chunk-size=0B # Maximum size of data buffers used for writing to the response.
spring.thymeleaf.reactive.media-types=# Media types supported by the view technology.
spring.thymeleaf.render-hidden-markers-before-checkboxes=false # Whether hidden form inputs acting as markers for checkboxes should be rendered before the checkbox element itself.
spring.thymeleaf.servlet.content-type=text/html # Content-Type value written to HTTP responses.
spring.thymeleaf.servlet.produce-partial-output-while-processing=true # Whether Thymeleaf should start writing partial output as soon as possible or buffer until template processing is finished.
spring.thymeleaf.suffix=.html # Suffix that gets appended to view names when building a URL.
spring.thymeleaf.template-resolver-order=# Order of the template resolver in the chain.
spring.thymeleaf.view-names=# Comma-separated list of view names (patterns allowed) that can be resolved.
maven引入依賴(lài)
<!--Thymeleaf模板依賴(lài)-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
項(xiàng)目結(jié)構(gòu)
thymeleaf默認(rèn),頁(yè)面跳轉(zhuǎn)默認(rèn)路徑:src/main/resources/templates,靜態(tài)資源默認(rèn)路徑:src/main/resources/static;
yml配置文件
我們也可以在配置文件中修改它:classpath:/view/
controller頁(yè)面跳轉(zhuǎn)
使用ModelAndView進(jìn)行跳轉(zhuǎn),將數(shù)據(jù)add進(jìn)去
@RequestMapping("/login.do")
public ModelAndView login(User user){
Result result=userService.login(user);
ModelAndView mv=new ModelAndView();
mv.addObject("newText","你好,Thymeleaf!");
mv.addObject("gender","1");
mv.addObject("userList",result.getData());
if(result.getData()!=null) {
mv.addObject("loginUser",result.getData());
}
mv.setViewName("index.html");
return mv;
}
html頁(yè)面取值
引入命名空間,避免校驗(yàn)錯(cuò)誤<html xmlns:th="http://www.thymeleaf.org">
<!DOCTYPE html>
<!--解決idea thymeleaf 表達(dá)式模板報(bào)紅波浪線(xiàn)-->
<!--suppress ALL -->
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8" />
<title>srpingboot</title>
</head>
<body>
<!-- 屬性替換,其他屬性同理 -->
<h1 th:text="${newText}">Hello World</h1>
<!--
設(shè)置多個(gè)attr
th:attr="id=${user.id},data-xxx=${user.xxx},data-yyy=${user.yyy}"
片段的使用、傳值和調(diào)用
<div th:fragment="common(text1,text2)">
...
</div>
th:insert 是最簡(jiǎn)單的:它只是插入指定的片段作為其主機(jī)標(biāo)簽的主體。
<div th:insert="base ::common(${text1},${text2})"></div>
th:replace實(shí)際上用指定的片段替換它的主機(jī)標(biāo)簽。
<div th:replace="base ::common(${text1},${text2})"></div>
三目表達(dá)式:
<h3 th:text="${loginUser !=null} ? ${loginUser.username} : '請(qǐng)登錄'"></h3>
-->
<!-- if-else -->
<h3 th:if="${loginUser} ne null" th:text="${loginUser.username}"></h3>
<h3 th:unless="${loginUser} ne null">請(qǐng)登錄</h3>
<!-- switch -->
<div th:switch="${gender}">
<p th:case="'1'">男</p>
<p th:case="'0'">女</p>
<!-- th:case="*" 類(lèi)似switch中的default -->
<p th:case="*">其他</p>
</div>
<!--
each
其中,iterStat參數(shù)為狀態(tài)變量,常用的屬性有
index 迭代下標(biāo),從0開(kāi)始
count 迭代下標(biāo),從1開(kāi)始
size 迭代元素的總量
current 當(dāng)前元素
-->
<table>
<thead>
<tr>
<th>id</th>
<th>username</th>
<th>password</th>
<th>created</th>
<th>description</th>
</tr>
</thead>
<tbody>
<tr th:each="user,iterStat : ${userList}">
<td th:text="${user.id}"></td>
<td th:text="${user.username}"></td>
<td th:text="${user.password}"></td>
<td th:text="${user.created}"></td>
<td th:text="${user.description}"></td>
</tr>
</tbody>
</table>
</body>
<!-- 引入靜態(tài)資源 -->
<script th:src="@{/js/jquery-1.9.1.min.js}" type="application/javascript"></script>
</html>
本地打開(kāi)
服務(wù)容器打開(kāi),登錄失敗頁(yè)面效果
服務(wù)容器打開(kāi),登錄成功頁(yè)面效果
簡(jiǎn)單表達(dá)
變量表達(dá)式: ${...}
選擇變量表達(dá)式: *{...}
消息表達(dá)式: #{...}
鏈接網(wǎng)址表達(dá)式: @{...}
片段表達(dá)式: ~{...}
字面
文本文字:'one text','Another one!',...
號(hào)碼文字:0,34,3.0,12.3,...
布爾文字:true,false
空字面: null
文字標(biāo)記:one,sometext,main,...
文字操作:
字符串連接: +
文字替換: |The name is ${name}|
算術(shù)運(yùn)算
二元運(yùn)算符:+,-,*,/,%
減號(hào)(一元運(yùn)算符): -
布爾運(yùn)算
二元運(yùn)算符:and,or
布爾否定(一元運(yùn)算符): !,not
比較和平等
比較:>,<,>=,<=(gt,lt,ge,le)
等值運(yùn)算符:==,!=(eq,ne)
條件運(yùn)算符
if-then: (if) ? (then)
if-then-else: (if) ? (then) : (else)
default: (value) ?: (defaultvalue)
特殊特征符
無(wú)操作: _
所有這些功能都可以組合和嵌套,例:
'User is of type ' + (user.isAdmin()?′Administrator′:(user.isAdmin()?′Administrator′:({user.type} ?: 'Unknown'))
官網(wǎng)表達(dá)式介紹:https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#standard-expression-syntax
springboot+thymeleaf,前后端分離已經(jīng)成為了趨勢(shì),這里進(jìn)行學(xué)習(xí)記錄整理,以免以后又要到處查資料。
2019-07-24補(bǔ)充:除此之外,thymeleaf還內(nèi)置了很多對(duì)象,可以從上下文獲取數(shù)據(jù),還有好多對(duì)象的操作方法,具體請(qǐng)看:
附錄A:表達(dá)式基本對(duì)象:https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#appendix-a-expression-basic-objects
附錄B:表達(dá)式實(shí)用程序?qū)ο螅篽ttps://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#appendix-b-expression-utility-objects
比如:
在頁(yè)面獲取項(xiàng)目路徑
//項(xiàng)目路徑
var ctx=[[${#request.getContextPath()}]];
判斷集合長(zhǎng)度
<p th:if="${#lists.size(list)} < 25">
<p>list集合長(zhǎng)度小于25!</p>
</p>
字符串全大寫(xiě)、小寫(xiě)
<p th:text="${#strings.toUpperCase(name)}"></p>
<p th:text="${#strings.toLowerCase(name)}"></p>
有一點(diǎn)要注意,使用這些內(nèi)置對(duì)象,方法傳參里面不需要再用${}來(lái)取值了,例如,后臺(tái)傳過(guò)來(lái)的名稱(chēng)叫name
錯(cuò)誤使用:
<p th:text="${#strings.toUpperCase($(name))}"></p>
正確使用:
<p th:text="${#strings.toUpperCase(name)}"></p>
更多內(nèi)置對(duì)象方法請(qǐng)看官網(wǎng)!
補(bǔ)充:本地環(huán)境不報(bào)錯(cuò),Linux環(huán)境下報(bào)錯(cuò),模板不存在:Error resolving template [/bam/login], template might not exist or might not be accessible by any of the configured Template Resolvers
解決:
把/去掉就可以了
代碼已經(jīng)開(kāi)源、托管到我的GitHub、碼云:
GitHub:https://github.com/huanzi-qch/springBoot
碼云:https://gitee.com/huanzi-qch/springBoot
作者:huanzi-qch
出處:https://www.cnblogs.com/huanzi-qch
若標(biāo)題中有“轉(zhuǎn)載”字樣,則本文版權(quán)歸原作者所有。若無(wú)轉(zhuǎn)載字樣,本文版權(quán)歸作者所有,歡迎轉(zhuǎn)載,但未經(jīng)作者同意必須保留此段聲明,且在文章頁(yè)面明顯位置給出原文鏈接,否則保留追究法律責(zé)任的權(quán)利.
文:https://www.xncoding.com/2017/07/01/spring/sb-thymeleaf.html
Thymeleaf 是一個(gè)跟 Velocity、FreeMarker 類(lèi)似的模板引擎,它可以完全替代 JSP 。相較與其他的模板引擎,它有如下三個(gè)極吸引人的特點(diǎn):
目前最新版本是Thymeleaf 3,官網(wǎng)地址:http://www.thymeleaf.org
本篇將介紹如何在SpringBoot中集成Thymeleaf構(gòu)建Web應(yīng)用。
maven依賴(lài)
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<thymeleaf.version>3.0.7.RELEASE</thymeleaf.version>
<thymeleaf-layout-dialect.version>2.2.2</thymeleaf-layout-dialect.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jetty</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
</dependencies>
資源目錄
Spring Boot默認(rèn)提供靜態(tài)資源目錄位置需置于classpath下,目錄名需符合如下規(guī)則:
舉例:我們可以在src/main/resources/目錄下創(chuàng)建static,在該位置放置一個(gè)圖片文件pic.jpg。 啟動(dòng)程序后,嘗試訪問(wèn)http://localhost:8080/pic.jpg。如能顯示圖片,配置成功。
SpringBoot的默認(rèn)模板路徑為:src/main/resources/templates
添加頁(yè)面
這里我在src/main/resources/templates下面添加一個(gè)index.html首頁(yè),同時(shí)引用到一些css、js文件,看看Thymeleaf 3的語(yǔ)法:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="renderer" content="webkit">
<title>首頁(yè)</title>
<link rel="shortcut icon" th:href="@{/favicon.ico}"/>
<link th:href="@{/static/css/bootstrap.min.css}" rel="stylesheet"/>
<link th:href="@{/static/css/font-awesome.min.css}" rel="stylesheet"/>
</head>
<body class="fixed-sidebar full-height-layout gray-bg" style="overflow:hidden">
<div id="wrapper">
<h1 th:text="${msg}"></h1>
</div>
<script th:src="@{/static/js/jquery.min.js}"></script>
<script th:src="@{/static/js/bootstrap.min.js}"></script>
</body>
</html>
頁(yè)面中幾個(gè)地方說(shuō)明一下:
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
加上這個(gè)命名空間后就能在頁(yè)面中使用Thymeleaf自己的標(biāo)簽了,以th:開(kāi)頭。
連接語(yǔ)法 th:href="@{/static/css/bootstrap.min.css}"
訪問(wèn)Model中的數(shù)據(jù)語(yǔ)法 th:text="${msg}"
這里我在頁(yè)面里顯示的是一個(gè)鍵為msg的消息,需要后臺(tái)傳遞過(guò)來(lái)。
Thymeleaf 3的詳細(xì)語(yǔ)法規(guī)則請(qǐng)參考 官網(wǎng)教程
編寫(xiě)Controller
接下來(lái)編寫(xiě)控制器類(lèi),將URL / 和 /index 都返回index.html頁(yè)面:
@Controller
public class IndexController {
private static final Logger _logger=LoggerFactory.getLogger(IndexController.class);
/**
* 主頁(yè)
*
* @param model
* @return
*/
@RequestMapping({"/", "/index"})
public String index(Model model) {
model.addAttribute("msg", "welcome you!");
return "index";
}
}
這里,我再model里面添加了一個(gè)屬性,key=msg,值為welcome you!。
接下來(lái)啟動(dòng)應(yīng)用后,打開(kāi)首頁(yè)看看效果如何。消息正確顯示,成功!。
Thymeleaf 是新一代 Java 模板引擎,與 Velocity、FreeMarker 等傳統(tǒng) Java 模板引擎不同,Thymeleaf 支持 HTML 原型,其文件后綴為“.html”,因此它可以直接被瀏覽器打開(kāi),此時(shí)瀏覽器會(huì)忽略未定義的 Thymeleaf 標(biāo)簽屬性,展示 thymeleaf 模板的靜態(tài)頁(yè)面效果;當(dāng)通過(guò) Web 應(yīng)用程序訪問(wèn)時(shí),Thymeleaf 會(huì)動(dòng)態(tài)地替換掉靜態(tài)內(nèi)容,使頁(yè)面動(dòng)態(tài)顯示。
html<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<!--th:text 為 Thymeleaf 屬性,用于在展示文本-->
<h1 th:text="歡迎您來(lái)到Thymeleaf">歡迎您訪問(wèn)靜態(tài)頁(yè)面 HTML</h1>
</body>
</html>
當(dāng)直接使用瀏覽器打開(kāi)時(shí),瀏覽器展示結(jié)果如下。
歡迎您訪問(wèn)靜態(tài)頁(yè)面HTML
當(dāng)通過(guò) Web 應(yīng)用程序訪問(wèn)時(shí),瀏覽器展示結(jié)果如下。
歡迎您來(lái)到Thymeleaf
Thymeleaf 的特點(diǎn):
在使用 Thymeleaf 之前,首先要在頁(yè)面的 html 標(biāo)簽中聲明名稱(chēng)空間,示例代碼如下。
htmlxmlns:th="http://www.thymeleaf.org"
在 html 標(biāo)簽中聲明此名稱(chēng)空間,可避免編輯器出現(xiàn) html 驗(yàn)證錯(cuò)誤,但這一步并非必須進(jìn)行的,即使我們不聲明該命名空間,也不影響 Thymeleaf 的使用。
使用${}包裹的表達(dá)式被稱(chēng)為變量表達(dá)式,該表達(dá)式具有以下功能:
選擇變量表達(dá)式與變量表達(dá)式功能基本一致,只是在變量表達(dá)式的基礎(chǔ)上增加了與 th:object 的配合使用。當(dāng)使用 th:object 存儲(chǔ)一個(gè)對(duì)象后,我們可以在其后代中使用選擇變量表達(dá)式(*{...})獲取該對(duì)象中的屬性,其中,“*”即代表該對(duì)象。
html<div th:object="${session.user}" >
<p th:text="*{fisrtName}">firstname</p>
</div>
th:object 用于存儲(chǔ)一個(gè)臨時(shí)變量,該變量只在該標(biāo)簽及其后代中有效,在后面的內(nèi)容“th 屬性”中我詳細(xì)介紹。
不管是靜態(tài)資源的引用,還是 form 表單的請(qǐng)求,凡是鏈接都可以用鏈接表達(dá)式 (@{...})。
鏈接表達(dá)式的形式結(jié)構(gòu)如下:
例如使用鏈接表達(dá)式引入 css 樣式表,代碼如下。
html<link href="asserts/css/signin.css" th:href="@{/asserts/css/signin.css}" rel="stylesheet">
消息表達(dá)式一般用于國(guó)際化的場(chǎng)景。結(jié)構(gòu)如下。
htmlth:text="#{msg}"
注意:此處了解即可,我們會(huì)在后面的章節(jié)中詳細(xì)介紹。
片段引用表達(dá)式用于在模板頁(yè)面中引用其他的模板片段,該表達(dá)式支持以下 2 中語(yǔ)法結(jié)構(gòu):
以上語(yǔ)法結(jié)構(gòu)說(shuō)明如下:
Thymeleaf 還提供了大量的 th 屬性,這些屬性可以直接在 HTML 標(biāo)簽中使用,其中常用 th 屬性及其示例如下表。
屬性 | 描述 | 示例 |
th:id | 替換 HTML 的 id 屬性 | <input id="html-id" th:id="thymeleaf-id" /> |
th:text | 文本替換,轉(zhuǎn)義特殊字符 | <h1 th:text="hello,bianchengbang" >hello</h1> |
th:untext | 文本替換,文本替換,不轉(zhuǎn)義特殊字符 | <div th:utext="'<h1>歡迎來(lái)到編程幫!</h1>'" >歡迎你</div> |
th:object | 在父標(biāo)簽選擇對(duì)象,子標(biāo)簽使用 *{…} 選擇表達(dá)式選取值。沒(méi)有選擇對(duì)象,那子標(biāo)簽使用選擇表達(dá)式和 ${…} 變量表達(dá)式是一樣的效果。同時(shí)即使選擇了對(duì)象,子標(biāo)簽仍然可以使用變量表達(dá)式。 | <div th:object="${session.user}" > <p th:text="*{fisrtName}">firstname</p> </div> |
th:value | 替換 value 屬性 | <input th:value="${user.name}" /> |
th:with | 局部變量賦值運(yùn)算 | <div th:with="isEvens=${prodStat.count}%2==0" th:text="${isEvens}"></div> |
th:style | 設(shè)置樣式 | <div th:style="'color:#F00; font-weight:bold'">編程幫 www.biancheng.net</div> |
th:onclick | 點(diǎn)擊事件 | <td th:onclick="'getInfo()'"></td> |
th:each | 遍歷,支持 Iterable、Map、數(shù)組等。 | <table> <tr th:each="m:${session.map}"> <td th:text="${m.getKey()}"></td> <td th:text="${m.getValue()}"></td> </tr></table> |
th:if | 根據(jù)條件判斷是否需要展示此標(biāo)簽 | <a th:if="${userId==collect.userId}"> |
th:unless | 和 th:if 判斷相反,滿(mǎn)足條件時(shí)不顯示 | <div th:unless="${m.getKey()=='name'}" ></div> |
th:switch | 與 Java 的 switch case語(yǔ)句類(lèi)似通常與 th:case 配合使用,根據(jù)不同的條件展示不同的內(nèi)容 | <div th:switch="${name}"> <span th:case="a">編程幫</span> <span th:case="b">www.biancheng.net</span></div> |
th:fragment | 模板布局,類(lèi)似 JSP 的 tag,用來(lái)定義一段被引用或包含的模板片段 | <footer th:fragment="footer">插入的內(nèi)容</footer> |
th:insert | 布局標(biāo)簽;將使用 th:fragment 屬性指定的模板片段(包含標(biāo)簽)插入到當(dāng)前標(biāo)簽中 | <div th:insert="commons/bar::footer"></div> |
th:replace | 布局標(biāo)簽;使用 th:fragment 屬性指定的模板片段(包含標(biāo)簽)替換當(dāng)前整個(gè)標(biāo)簽 | <div th:replace="commons/bar::footer"></div> |
th:selected | select 選擇框選中 | <select> <option>---</option> <option th:selected="${name=='a'}"> 編程幫 </option> <option th:selected="${name=='b'}"> www.biancheng.net </option></select> |
th:src | 替換 HTML 中的 src 屬性 | <img th:src="@{/asserts/img/bootstrap-solid.svg}" src="asserts/img/bootstrap-solid.svg" /> |
th:inline | 內(nèi)聯(lián)屬性;該屬性有 text、none、javascript 三種取值,在 <script> 標(biāo)簽中使用時(shí),js 代碼中可以獲取到后臺(tái)傳遞頁(yè)面的對(duì)象。 | <script type="text/javascript" th:inline="javascript"> var name=/*[[${name}]]*/ ianchengbang'; alert(name)</script> |
th:action | 替換表單提交地址 | <form th:action="@{/user/login}" th:method="post"></form> |
在 Web 項(xiàng)目中,通常會(huì)存在一些公共頁(yè)面片段(重復(fù)代碼),例如頭部導(dǎo)航欄、側(cè)邊菜單欄和公共的 js css 等。我們一般會(huì)把這些公共頁(yè)面片段抽取出來(lái),存放在一個(gè)獨(dú)立的頁(yè)面中,然后再由其他頁(yè)面根據(jù)需要進(jìn)行引用,這樣可以消除代碼重復(fù),使頁(yè)面更加簡(jiǎn)潔。
Thymeleaf 作為一種優(yōu)雅且高度可維護(hù)的模板引擎,同樣支持公共頁(yè)面的抽取和引用。我們可以將公共頁(yè)面片段抽取出來(lái),存放到一個(gè)獨(dú)立的頁(yè)面中,并使用 Thymeleaf 提供的 th:fragment 屬性為這些抽取出來(lái)的公共頁(yè)面片段命名。 示例 1 將公共頁(yè)面片段抽取出來(lái),存放在 commons.html 中,代碼如下。
html<div th:fragment="fragment-name" id="fragment-id">
<span>公共頁(yè)面片段</span>
</div>
在 Thymeleaf 中,我們可以使用以下 3 個(gè)屬性,將公共頁(yè)面片段引入到當(dāng)前頁(yè)面中。
使用上 3 個(gè)屬性引入頁(yè)面片段,都可以通過(guò)以下 2 種方式實(shí)現(xiàn)。
通常情況下,
{} 可以省略,其行內(nèi)寫(xiě)法為 [[{...}]] 或 [({...})],其中 [[{...}]] 會(huì)轉(zhuǎn)義特殊字符,[(~{...})] 則不會(huì)轉(zhuǎn)義特殊字符。
示例 2
html<!--th:insert 片段名引入-->
<div th:insert="commons::fragment-name"></div>
<!--th:insert id 選擇器引入-->
<div th:insert="commons::#fragment-id"></div>
------------------------------------------------
<!--th:replace 片段名引入-->
<div th:replace="commons::fragment-name"></div>
<!--th:replace id 選擇器引入-->
<div th:replace="commons::#fragment-id"></div>
------------------------------------------------
<!--th:include 片段名引入-->
<div th:include="commons::fragment-name"></div>
<!--th:include id 選擇器引入-->
<div th:include="commons::#fragment-id"></div>
html<!--th:insert 片段名引入-->
<div>
<div id="fragment-id">
<span>公共頁(yè)面片段</span>
</div>
</div>
<!--th:insert id 選擇器引入-->
<div>
<div id="fragment-id">
<span>公共頁(yè)面片段</span>
</div>
</div>
------------------------------------------------
<!--th:replace 片段名引入-->
<div id="fragment-id">
<span>公共頁(yè)面片段</span>
</div>
<!--th:replace id 選擇器引入-->
<div id="fragment-id">
<span>公共頁(yè)面片段</span>
</div>
------------------------------------------------
<!--th:include 片段名引入-->
<div>
<span>公共頁(yè)面片段</span>
</div>
<!--th:include id 選擇器引入-->
<div>
<span>公共頁(yè)面片段</span>
</div>
Thymeleaf 在抽取和引入公共頁(yè)面片段時(shí),還可以進(jìn)行參數(shù)傳遞,大致步驟如下: 1.傳入?yún)?shù); 2.使用參數(shù)。
引用公共頁(yè)面片段時(shí),我們可以通過(guò)以下 2 種方式,將參數(shù)傳入到被引用的頁(yè)面片段中: 模板名::選擇器名或片段名(參數(shù)1=參數(shù)值1,參數(shù)2=參數(shù)值2) 模板名::選擇器名或片段名(參數(shù)值1,參數(shù)值2)
注:若傳入?yún)?shù)較少時(shí),一般采用第二種方式,直接將參數(shù)值傳入頁(yè)面片段中; 若參數(shù)較多時(shí),建議使用第一種方式,明確指定參數(shù)名和參數(shù)值,。
示例代碼如下:
java<!--th:insert 片段名引入-->
<div th:insert="commons::fragment-name(var1='insert-name',var2='insert-name2')"></div>
<!--th:insert id 選擇器引入-->
<div th:insert="commons::#fragment-id(var1='insert-id',var2='insert-id2')"></div>
------------------------------------------------
<!--th:replace 片段名引入-->
<div th:replace="commons::fragment-name(var1='replace-name',var2='replace-name2')"></div>
<!--th:replace id 選擇器引入-->
<div th:replace="commons::#fragment-id(var1='replace-id',var2='replace-id2')"></div>
------------------------------------------------
<!--th:include 片段名引入-->
<div th:include="commons::fragment-name(var1='include-name',var2='include-name2')"></div>
<!--th:include id 選擇器引入-->
<div th:include="commons::#fragment-id(var1='include-id',var2='include-id2')"></div>
在聲明頁(yè)面片段時(shí),我們可以在片段中聲明并使用這些參數(shù),例如:
java<!--使用 var1 和 var2 聲明傳入的參數(shù),并在該片段中直接使用這些參數(shù) -->
<div th:fragment="fragment-name(var1,var2)" id="fragment-id">
<p th:text="'參數(shù)1:'+${var1} + '-------------------參數(shù)2:' + ${var2}">...</p>
</div>
啟動(dòng) Spring Boot,使用瀏覽器訪問(wèn) fragment.html,結(jié)果如下圖。
*請(qǐng)認(rèn)真填寫(xiě)需求信息,我們會(huì)在24小時(shí)內(nèi)與您取得聯(lián)系。