Spring Boot2學(xué)習(xí)筆記--thymeleaf

摘要

看完本文你將掌握如下知識點:

項目準(zhǔn)備

依賴

<!--spring對thymeleaf的支持-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

開啟spring boot對thymeleaf的支持

##thymeleaf
spring.thymeleaf.enabled=true
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.mode=HTML
#關(guān)閉頁面緩存
spring.thymeleaf.cache=false
spring.thymeleaf.servlet.content-type=text/html

也可以通過@Bean的方式開啟支持

    @Bean
    public ThymeleafViewResolver thymeleafViewResolver(){
        log.info("thymeleafViewResolver");
        ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
        viewResolver.setTemplateEngine(templateEngine());
        viewResolver.setOrder(1);
        viewResolver.setCharacterEncoding("UTF-8");
        viewResolver.setContentType("text/html");
        viewResolver.setCache(false);
        return viewResolver;
    }

    @Bean
    public SpringResourceTemplateResolver templateResolver(){
        SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
        templateResolver.setApplicationContext(this.applicationContext);
        templateResolver.setPrefix("classpath:/templates/");
        templateResolver.setSuffix(".html");        
        templateResolver.setTemplateMode(TemplateMode.HTML);
        templateResolver.setCacheable(false);
        return templateResolver;
    }

    @Bean
    public SpringTemplateEngine templateEngine(){
        SpringTemplateEngine templateEngine = new SpringTemplateEngine();
        templateEngine.setTemplateResolver(templateResolver());
        templateEngine.setEnableSpringELCompiler(true);
        return templateEngine;
    }

開啟html頁面對thymeleaf語法的支持

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
</html>

語法

各種表達式語法

1.${...} 變量表達式放吩,用于展示后臺傳遞過來的變量(request和session中的值)

<input type="text" name="modify" th:value="${modify}"/>
<input type="text" name="id" th:value="${dataObj.id}"/>
<textarea  name="logParamData" id="logParamData" th:text="${dataObj.logParamData}"></textarea>

以下兩種方式效果一致
<span th:text="${dataObj.name}"></span>
<span>[[${dataObj.name}]]</span>

字符串拼接损离,可以使用加號蓖柔,也可以使用豎線挖滤,以下兩種方式效果一致
<input type="checkbox" name="accessTypes" th:value="${item.id}+'_'+${type.id}" checked="checked"> [[${type.name}]
<input type="checkbox" name="accessTypes" th:value="${|${item.id}_${type.id}|}" checked="checked"> [[${type.name}]

#dates與java.util.Date對象的方法對應(yīng)捣卤,格式化渔肩、日期組件抽取等等
<td th:text="${#dates.format(item.logTime, 'yyyy-MM-dd')}"></td>
<td>[[${#dates.format(item.logTime, 'yyyy-MM-dd')}]]</td>

2.#{...} 國際化消息表達式捉蚤,用于展示message.properties等國際化資源文件中的內(nèi)容

<input type="checkbox" name="selectAll" id="selectAll" th:text="#{common.choose}"/>

消息中需要傳遞變量的情況揉稚,多個變量逗號分割
<strong th:text="#{common.page.summary(${_pageBean.pageCount},${_pageBean.total})}">

以下兩種方式效果一致
<td th:text="#{common.operate}"></td>
<td>[[#{common.operate}]]</td>

3.@{...} 鏈接url表達式厨相,用于封裝url领曼,如contextPath補全

<link th:href="@{/resource/css/netqin.css}" rel="stylesheet"/>
用兩個豎線來拼接帶表達式的字符串
<script type="text/javascript" th:src="@{|/resource/js/i18n/list.#{locale}.js|}"></script>
帶請求參數(shù)的url,多個用逗號分割
<a th:href="@{/auth/systemLogger/edit.do(id=${item.id},flag=${flag})}" th:text="#{common.edit}"></a>

4.js和css中用到表達式時使用雙中括號的方式

var modify = "[[${modify}]]";
if(modify != "add"){
    $("#password").attr("placeholder","[[#{user.detail.changeNotice}]]");
}

5.*{...} 選擇變量表達式蛮穿,用于簡寫變量名稱庶骄,需要配合th:object一起使用

<div th:object="${user}">
    <p>firstName: <span th:text="*{firstName}"></span></p>
    <p>lastName: <span th:text="*{lastName}"></span></p>
</div>
相當(dāng)于
<div>
    <p>firstName: <span th:text="${user.firstName}"></span></p>
    <p>lastName: <span th:text="${user.lastName}"></span></p>
</div>

6.~{...} 代碼塊表達式,用于在html中復(fù)用相同的結(jié)構(gòu)
語法:~{templatename::fragmentname}
示例:
common/model.html践磅,th:fragment="header"指定代碼塊名稱

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head th:fragment="header">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<META http-equiv="Pragma" content="no-cache">
<META http-equiv="Cache-Control" content="no-cache">
<META http-equiv="Expire" content="0">
<link th:href="@{/resource/css/bootstrap.min.css}" rel="stylesheet" />
<link th:href="@{/resource/css/ace.min.css}" rel="stylesheet" />
<link rel="stylesheet" th:href="@{/resource/css/font-awesome.min.css}" />
<script th:src="@{/resource/js/jquery-1.11.0.min.js}"></script>
</head>
<body>
</body>
</html>

demo.html单刁,th:replace="common/model::header",模板名稱::代碼塊名稱

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<header th:replace="common/model::header"></header>
<body>
</body>
</html>

說明:代碼塊表達式需要配合th屬性(th:insert府适,th:replace羔飞,th:include)一起使用。

th:insert:將代碼塊片段整個插入到使用了th:insert的HTML標(biāo)簽中细溅,
th:replace:將代碼塊片段整個替換使用了th:replace的HTML標(biāo)簽中褥傍,
th:include:將代碼塊片段包含的內(nèi)容插入到使用了th:include的HTML標(biāo)簽中,

遍歷

簡單示例

<tr th:each="item:${results}">
<td>
    <input type="checkbox" name="ids" th:value="${item.id}" class="noborder"/>
</td>
<td th:text="${item.id}"></td>
<td>
    [[${#dates.format(item.logTime, 'yyyy-MM-dd')}]]
</td>
<td th:text="${item.logDesc}"></td>
<td th:text="${item.logUser}"></td>
</tr>

帶遍歷狀態(tài)的示例

<tr th:each="item,status:${results}" th:class="${status.odd}? 'odd':'even'">
<td>
    <input type="checkbox" name="ids" th:value="${item.id}" class="noborder"/>
</td>
<td th:text="${item.id}"></td>
<td>
    [[${#dates.format(item.logTime, 'yyyy-MM-dd')}]]
</td>
<td th:text="${item.logDesc}"></td>
<td th:text="${item.logUser}"></td>
</tr>
  • 狀態(tài)說明
  index:當(dāng)前遍歷索引喇聊,從0開始
  count:當(dāng)前遍歷索引恍风,從1開始
  size:總元素數(shù)量
  current:每一次遍歷的iter變量
  even/odd:當(dāng)前遍歷是even還是odd,布爾屬性
  first:當(dāng)前遍歷是第一個,布爾屬性
  last:當(dāng)前遍歷是最后一個朋贬,布爾屬性

遍歷時可以自定義變量

th:with:用于定義變量凯楔,多個使用逗號分割
<span th:each="type,status:${accessTypes}" th:with="shwoName=${item.id}+'_'+${item.name}">
[[${shwoName}]]
<span th:if="${not status.last}">,</span>  
</span>

條件判斷

th:if

判斷為true時才會顯示div,authorities為Set類型锦募,所以判斷是否包含時可以使用#sets.contains()方法摆屯,測試時發(fā)現(xiàn)使用#arrays.contains()方法時也可以
<div th:if="${dataObj.reserved}">
    <li th:each="item:${dataObj.authorities}">
        <input type="checkbox" name="authorities" th:value="${item.id}"
              th:if="${dataObj.authorities ==null or not #sets.contains(dataObj.authorities,item)}">
        <input type="checkbox" name="authorities" th:value="${item.id}"
              checked="checked" th:if="${dataObj.authorities !=null and #sets.contains(dataObj.authorities,item)}">
        <span th:text="${item.showNameRole}"></span>
    </li>
</div>

如果要判斷為false時才會顯示div,可以判斷值是否等于false糠亩,或者使用th:unless
<div th:if="${dataObj.reserved==false}">
    <li th:each="item:${dataObj.authorities}">
        <input type="checkbox" name="authorities" th:value="${item.id}"><span th:text="${item.showNameRole}"></span>
    </li>
</div>

<div th:unless="${dataObj.reserved}">
    <li th:each="item:${dataObj.authorities}">
        <input type="checkbox" name="authorities" th:value="${item.id}"><span th:text="${item.showNameRole}"></span>
    </li>
</div>

  • th:if 以下情況運算為true
  值不為null
  值為boolean且為true
  值為數(shù)字且非0
  值為字符且非0
  值是字符串且不是:“false”虐骑,“off”,“no”
  值是object,但不為null

th:switch 和 th:case

bool匹配
<div th:switch="${dataObj.reserved}">
    <p th:case="true">true</p>
    <p th:case="false">false</p>
</div>

字符串匹配赎线,要加單引號
<div th:switch="${item.showNameRole}">
    <p th:case="'admin'">administrator</p>
    <p th:case="'manager'">manager</p>
</div>

<div th:switch="${item.showNameRole}">
    <p th:case="'admin'">administrator</p>
    <p th:case="'manager'">manager</p>
    <p th:case="*">unknow</p>
</div>


  • 說明:th:case="*" 表示沒有匹配成功時顯示的內(nèi)容

運算符

  • 字符串連接
  + : ${item.id}+'_'+${type.id}
  |xxxx| : |The name is ${name}|
  • 算術(shù)運算
  + , - , * , / , %  (二元運算符)
  -  :負(fù)號(一元運算符)
  • 布爾操作
  and :且,or :或 (二元運算符)
  !,not :非(一元操作符)
  • 關(guān)系操作符
  > , < , >= , <= (gt , lt , ge , le)
  == , != (eq, ne)

表達式工具對象

  #dates 與java.util.Date對象的方法對應(yīng)廷没,格式化、日期組件抽取等等
  #calendars 類似#dates垂寥,與java.util.Calendar對象對應(yīng)
  #numbers 格式化數(shù)字對象的工具方法
  #strings 與java.lang.String對應(yīng)的工具方法:contains颠黎、startsWith、prepending/appending等等
  #objects 用于對象的工具方法
  #bools 用于布爾運算的工具方法
  #arrays 用于數(shù)組的工具方法
  #lists 用于列表的工具方法
  #sets 用于set的工具方法
  #maps 用于map的工具方法
  #aggregates 用于創(chuàng)建數(shù)組或集合的聚合的工具方法
  #messages 用于在變量表達式內(nèi)部獲取外化消息的工具方法滞项,與#{…}語法獲取的方式相同
  #ids 用于處理可能重復(fù)出現(xiàn)(例如狭归,作為遍歷的結(jié)果)的id屬性的工具方法

使用springsecurity權(quán)限標(biāo)簽的方法

添加依賴

<!--如果項目中使用到了springsecurity4, 則要加入下面的依賴來使用權(quán)限標(biāo)簽-->
<dependency>
    <groupId>org.thymeleaf.extras</groupId>
    <artifactId>thymeleaf-extras-springsecurity4</artifactId>
    <version>3.0.2.RELEASE</version>
</dependency>

開啟命名空間支持

<html xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
</html>

使用方式與jsp標(biāo)簽類似:
<a th:href="@{/auth/systemLogger/edit.do}" class="btn btn-success btn-xs no-hover" th:text="#{common.create}" sec:authorize="hasRole('LOGGER_ADD')"></a>
<button class="btn btn-danger btn-xs" id="delete" th:text="#{common.delete}" sec:authorize="hasRole('LOGGER_DELETE')"></button>

調(diào)用spring管理的bean的方法

語法:${@beanName.methodName(param,...)}
說明:beanName就是注冊時的名稱
示例:

#httpSession就是javax.servlet.http.HttpSession對象
#httpServletRequest就是javax.servlet.http.HttpServletRequest對象
<span th:text="${@commonService.clearSessionMessage(#httpServletRequest)}" style="display: none"></span>

參考資料

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末文判,一起剝皮案震驚了整個濱河市过椎,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌律杠,老刑警劉巖潭流,帶你破解...
    沈念sama閱讀 218,546評論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異柜去,居然都是意外死亡灰嫉,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,224評論 3 395
  • 文/潘曉璐 我一進店門嗓奢,熙熙樓的掌柜王于貴愁眉苦臉地迎上來讼撒,“玉大人,你說我怎么就攤上這事股耽「校” “怎么了?”我有些...
    開封第一講書人閱讀 164,911評論 0 354
  • 文/不壞的土叔 我叫張陵物蝙,是天一觀的道長炎滞。 經(jīng)常有香客問我,道長诬乞,這世上最難降的妖魔是什么册赛? 我笑而不...
    開封第一講書人閱讀 58,737評論 1 294
  • 正文 為了忘掉前任钠导,我火速辦了婚禮,結(jié)果婚禮上森瘪,老公的妹妹穿的比我還像新娘牡属。我一直安慰自己,他們只是感情好扼睬,可當(dāng)我...
    茶點故事閱讀 67,753評論 6 392
  • 文/花漫 我一把揭開白布逮栅。 她就那樣靜靜地躺著,像睡著了一般窗宇。 火紅的嫁衣襯著肌膚如雪措伐。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,598評論 1 305
  • 那天军俊,我揣著相機與錄音废士,去河邊找鬼。 笑死蝇完,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的矗蕊。 我是一名探鬼主播短蜕,決...
    沈念sama閱讀 40,338評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼傻咖!你這毒婦竟也來了朋魔?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,249評論 0 276
  • 序言:老撾萬榮一對情侶失蹤卿操,失蹤者是張志新(化名)和其女友劉穎警检,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體害淤,經(jīng)...
    沈念sama閱讀 45,696評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡扇雕,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,888評論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了窥摄。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片镶奉。...
    茶點故事閱讀 40,013評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖崭放,靈堂內(nèi)的尸體忽然破棺而出哨苛,到底是詐尸還是另有隱情,我是刑警寧澤币砂,帶...
    沈念sama閱讀 35,731評論 5 346
  • 正文 年R本政府宣布建峭,位于F島的核電站,受9級特大地震影響决摧,放射性物質(zhì)發(fā)生泄漏亿蒸。R本人自食惡果不足惜凑兰,卻給世界環(huán)境...
    茶點故事閱讀 41,348評論 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望祝懂。 院中可真熱鬧票摇,春花似錦、人聲如沸砚蓬。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,929評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽灰蛙。三九已至祟剔,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間摩梧,已是汗流浹背物延。 一陣腳步聲響...
    開封第一講書人閱讀 33,048評論 1 270
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留仅父,地道東北人叛薯。 一個月前我還...
    沈念sama閱讀 48,203評論 3 370
  • 正文 我出身青樓,卻偏偏與公主長得像笙纤,于是被迫代替她去往敵國和親耗溜。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,960評論 2 355

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