十七囱晴、Spring Boot使用Thymeleaf模版引擎以及語法

1、模版引擎

JSP畸写,Velocity,F(xiàn)reemarker枯芬,Thymeleaf...

模版引擎.png

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等等卸例。

thymeleaf語法規(guī)則.png

? 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">
    &copy; 版權(quán)所有
</div>

? 2)瓶佳、引入公共片段

<div th:insert="~{footer :: copy}"></div>

~{templatename :: #selectorId} 表示:模版名::#選擇器id

代碼片段
<div id="copy-section">
    &copy; 2011 The Good Thymes Virtual Grocery
</div>

插入片段
<div th:insert="~{footer :: #copy-section}"></div>

~{templatename :: fragmentname} 表示:模版名::片段名

代碼片段
<div th:fragment="copy">
    &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">
    &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>
        &copy; 版權(quán)所有
    </footer>
</div>

th:replace效果
<footer>
    &copy; 版權(quán)所有
</footer>

th:include效果
<div>
    &copy; 版權(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散庶。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末凌净,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子泻蚊,更是在濱河造成了極大的恐慌,老刑警劉巖性雄,帶你破解...
    沈念sama閱讀 217,406評論 6 503
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異秒旋,居然都是意外死亡约计,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,732評論 3 393
  • 文/潘曉璐 我一進(jìn)店門迁筛,熙熙樓的掌柜王于貴愁眉苦臉地迎上來煤蚌,“玉大人,你說我怎么就攤上這事∥咀” “怎么了筒占?”我有些...
    開封第一講書人閱讀 163,711評論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長蜘犁。 經(jīng)常有香客問我翰苫,道長,這世上最難降的妖魔是什么这橙? 我笑而不...
    開封第一講書人閱讀 58,380評論 1 293
  • 正文 為了忘掉前任奏窑,我火速辦了婚禮,結(jié)果婚禮上屈扎,老公的妹妹穿的比我還像新娘埃唯。我一直安慰自己,他們只是感情好鹰晨,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,432評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著并村,像睡著了一般巍实。 火紅的嫁衣襯著肌膚如雪滓技。 梳的紋絲不亂的頭發(fā)上哩牍,一...
    開封第一講書人閱讀 51,301評論 1 301
  • 那天,我揣著相機(jī)與錄音令漂,去河邊找鬼膝昆。 笑死,一個胖子當(dāng)著我的面吹牛叠必,可吹牛的內(nèi)容都是我干的荚孵。 我是一名探鬼主播,決...
    沈念sama閱讀 40,145評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼纬朝,長吁一口氣:“原來是場噩夢啊……” “哼收叶!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起共苛,我...
    開封第一講書人閱讀 39,008評論 0 276
  • 序言:老撾萬榮一對情侶失蹤判没,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后隅茎,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體澄峰,經(jīng)...
    沈念sama閱讀 45,443評論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,649評論 3 334
  • 正文 我和宋清朗相戀三年辟犀,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了俏竞。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,795評論 1 347
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖魂毁,靈堂內(nèi)的尸體忽然破棺而出玻佩,到底是詐尸還是另有隱情,我是刑警寧澤席楚,帶...
    沈念sama閱讀 35,501評論 5 345
  • 正文 年R本政府宣布夺蛇,位于F島的核電站,受9級特大地震影響酣胀,放射性物質(zhì)發(fā)生泄漏刁赦。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,119評論 3 328
  • 文/蒙蒙 一闻镶、第九天 我趴在偏房一處隱蔽的房頂上張望甚脉。 院中可真熱鬧,春花似錦铆农、人聲如沸牺氨。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,731評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽猴凹。三九已至,卻和暖如春岭皂,著一層夾襖步出監(jiān)牢的瞬間郊霎,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,865評論 1 269
  • 我被黑心中介騙來泰國打工爷绘, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留书劝,地道東北人。 一個月前我還...
    沈念sama閱讀 47,899評論 2 370
  • 正文 我出身青樓土至,卻偏偏與公主長得像购对,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子陶因,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,724評論 2 354

推薦閱讀更多精彩內(nèi)容