1、模版引擎
JSP畸写,Velocity,F(xiàn)reemarker枯芬,Thymeleaf...
Spring Boot推薦的模版引擎:Thymeleaf。
2狂魔、引入Thymeleaf依賴
<!-- 修改Spring Boot的默認(rèn)版本 -->
<thymeleaf.version>3.0.9.RELEASE</thymeleaf.version>
<!-- 布局功能的支持程序
thymeleaf3 對應(yīng)layout2版本
thymeleaf2 對應(yīng)layout1版本
-->
<thymeleaf-layout-dialect.version>2.2.2</thymeleaf-layout-dialect.version>
<!-- thymeleaf模版引擎 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
3淫痰、Thymeleaf的使用&語法
ThymeleafProperties配置類:
@ConfigurationProperties(prefix = "spring.thymeleaf")
public class ThymeleafProperties {
//默認(rèn)編碼
private static final Charset DEFAULT_ENCODING = Charset.forName("UTF-8");
//文檔類型
private static final MimeType DEFAULT_CONTENT_TYPE = MimeType.valueOf("text/html");
//模版位置
public static final String DEFAULT_PREFIX = "classpath:/templates/";
//模版后綴
public static final String DEFAULT_SUFFIX = ".html";
private boolean checkTemplate = true;
private boolean checkTemplateLocation = true;
private String prefix = DEFAULT_PREFIX;
private String suffix = DEFAULT_SUFFIX;
private String mode = "HTML5";
private Charset encoding = DEFAULT_ENCODING;
private MimeType contentType = DEFAULT_CONTENT_TYPE;
//緩存
private boolean cache = true;
private Integer templateResolverOrder;
private String[] viewNames;
private String[] excludedViewNames;
private boolean enabled = true;
//other code...
}
只要把模版html放置在classpath:/templates/目錄下,thymeleaf就會自動渲染。
4烈评、使用Thymeleaf:
(1)犯建、導(dǎo)入thymeleaf的名稱空間:
<html lang="en" xmlns:th="http://www.thymeleaf.org"></html>
? (2)讲冠、thymeleaf語法:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div th:text="${hello}">這里是原來的文本适瓦!</div>
</body>
</html>
? (3)、語法規(guī)則:
? i)犹菇、th:text:改變當(dāng)前元素里面的文本內(nèi)容
th:任意html屬性:用來替換原生html屬性的值芽卿,例如id換成th:id, class換成th:class等等卸例。
? ii)、表達(dá)式:
Simple expressions:(表達(dá)式語法)
Variable Expressions: ${...}:獲取變量值姑原,OGNL表達(dá)式
1)呜舒、獲取對象的屬性锭汛、調(diào)用方法
2)袭蝗、使用內(nèi)置的基本對象
#ctx : the context object.
#vars: the context variables.
#locale : the context locale.
#request : (only in Web Contexts) the HttpServletRequest object.
#response : (only in Web Contexts) the HttpServletResponse object.
#session : (only in Web Contexts) the HttpSession object.
#servletContext : (only in Web Contexts) the ServletContext object.
3)、內(nèi)置的工具對象
#execInfo : information about the template being processed.
#messages : methods for obtaining externalized messages inside variables expressions, in the same way as they
would be obtained using #{…} syntax.
#uris : methods for escaping parts of URLs/URIs
#conversions : methods for executing the configured conversion service (if any).
#dates : methods for java.util.Date objects: formatting, component extraction, etc.
#calendars : analogous to #dates , but for java.util.Calendar objects.
#numbers : methods for formatting numeric objects.
#strings : methods for String objects: contains, startsWith, prepending/appending, etc.
#objects : methods for objects in general.
#bools : methods for boolean evaluation.
#arrays : methods for arrays.
#lists : methods for lists.
#sets : methods for sets.
#maps : methods for maps.
#aggregates : methods for creating aggregates on arrays or collections.
#ids : methods for dealing with id attributes that might be repeated (for example, as a result of an iteration)
Selection Variable Expressions: *{...}:選擇表達(dá)式朵逝,跟${}功能類似
補(bǔ)充功能:配合th:object進(jìn)行使用
<div th:object="${session.user}">
<p>Name: <span th:text="*{firstName}">Sebastian</span>.</p>
<p>Surname: <span th:text="*{lastName}">Pepper</span>.</p>
<p>Nationality: <span th:text="*{nationality}">Saturn</span>.</p>
</div>
Message Expressions: #{...}:獲取國際化內(nèi)容
Link URL Expressions: @{...}:定義URL鏈接
例子:@{/order/process(execId=${execId},execType='FAST')}
Fragment Expressions: ~{...}:片段引用表達(dá)式
Literals:
Text literals: 'one text' , 'Another one!' ,…
Number literals: 0 , 34 , 3.0 , 12.3 ,…
Boolean literals: true , false
Null literal: null
Literal tokens: one , sometext , main ,…
Text operations:
String concatenation: +
Literal substitutions: |The name is ${name}|
Arithmetic operations:
Binary operators: + , - , * , / , %
Minus sign (unary operator): -
Boolean operations:
Binary operators: and , or
Boolean negation (unary operator): ! , not
Comparisons and equality:
Comparators: > , < , >= , <= ( gt , lt , ge , le )
Equality operators: == , != ( eq , ne )
Conditional operators:
If-then: (if) ? (then)
If-then-else: (if) ? (then) : (else)
Default: (value) ?: (defaultvalue)
Special tokens:
No-Operation: _
? iii)配名、thymeleaf公共頁面元素抽取:
? 1)渠脉、抽取公共片段
<div th:fragment="copy">
© 版權(quán)所有
</div>
? 2)瓶佳、引入公共片段
<div th:insert="~{footer :: copy}"></div>
~{templatename :: #selectorId} 表示:模版名::#選擇器id
代碼片段
<div id="copy-section">
© 2011 The Good Thymes Virtual Grocery
</div>
插入片段
<div th:insert="~{footer :: #copy-section}"></div>
~{templatename :: fragmentname} 表示:模版名::片段名
代碼片段
<div th:fragment="copy">
© 2011 The Good Thymes Virtual Grocery
</div>
插入片段
<div th:insert="~{footer :: copy}"></div>
? 3)芋膘、默認(rèn)效果:insert的功能片段會被插入到div標(biāo)簽中。
如果使用th:insert等屬性進(jìn)行引入索赏,可以不用寫~{},可以直接寫templatename::#selectorId/fragmentname埃儿。
但是如果是行內(nèi)寫法,必須加上~{}童番, 如[[~{}]]威鹿。
三種引入公共片段的th屬性:
th:insert:將公共片段整個插入到聲明引入的元素中
th:replace:將聲明引入的元素替換為公共片段
th:include:將被引入的片段的內(nèi)容包含到引入的元素中
代碼片段
<footer th:fragment="copy">
© 版權(quán)所有
</footer>
引入方式
<div th:insert="~{footer::copy}"></div>
<div th:replace="~{footer::copy}"></div>
<div th:include="~{footer::copy}"></div>
實(shí)際效果:
th:insert效果
<div>
<footer>
© 版權(quán)所有
</footer>
</div>
th:replace效果
<footer>
© 版權(quán)所有
</footer>
th:include效果
<div>
© 版權(quán)所有
</div>
? (4)、在引入代碼片段的時(shí)候忽你,可以使用傳遞參數(shù)的方式,這樣在代碼片段中就可以使用傳遞過來的參數(shù)科雳。
<div th:fragment="frag">
...
</div>
<div th:replace="::frag (onevar=${value1},twovar=${value2})">
或
<div th:fragment="frag (onevar,twovar)">
<p th:text="${onevar} + ' - ' + ${twovar}">...</p>
</div>
<div th:replace="::frag (${value1},${value2})">...</div>
使用命名參數(shù)時(shí)順序不重要
<div th:replace="::frag (onevar=${value1},twovar=${value2})">...</div>
<div th:replace="::frag (twovar=${value2},onevar=${value1})">...</div>
比如,在templates/commons/bar.html中定義了如下代碼片段
<nav id="sidebar">
<a class="nav-link" th:class="${activeUrl == 'main' ? 'nav-link active' : 'nav-link'}" ...>
...
</a>
</nav>
在引入該代碼片段的時(shí)候简逮,可以使用傳遞參數(shù)的方式。
<div th:replace="commons/bar::#sidebar(activeUrl='main')">...</div>
或
<div th:replace="commons/bar::#sidebar(activeUrl='emps')">...</div>
至于其他Thymeleaf語法可以參考Thymeleaf官網(wǎng):http://www.thymeleaf.org散庶。