thymeleaf使用心得

thymeleaf使用心得

使用thymeleaf必須在HTML標(biāo)簽里加 xmlns:th="http://www.thymeleaf.org">

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

深入學(xué)習(xí)可以下載:Thymeleaf中文參考手冊

Maven

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>net.sourceforge.nekohtml</groupId>
            <artifactId>nekohtml</artifactId>
            <version>1.9.22</version>
        </dependency>

基礎(chǔ)

1. 屬性賦值

  1. 普通屬性:在前加th:即可 如:<div th:id='12'> (為id屬性賦值)
  2. 自定義屬性:要用 th:attr 如:<div th:attr="myParam='username'">

2. 獲取后端傳入對象屬性

用${對象.屬性}即可 ,不過若對線為空時就會報錯,所以在后端渲染數(shù)據(jù)時最好做出判斷,為null就new一個
對象。如 <input type='text' th:value='user.username'>

3. 邏輯語句

1.條件判斷

  • th:if 、 th:unless
    是相反的在if這邊為true的在unless就會為false

    寫法:
<th:block th:if="${user.username eq 'admin'}"></th:block><br>

也可以用其他標(biāo)簽 如:<a th:if="${user.username eq 'admin'}"></a> 如果判斷為false的話這個a標(biāo)簽就不會顯示

  • 條件賦值判斷
th:test = "${user.name eq 'admin'}?'管理員','游客'"

th:test = "${user.name}?:${other.name}"http://字有就顯示沒有就顯示后面的等同于
th:test = "${user.name}?${user.name}:${other.name}"

2. 循環(huán)語句

th:each="prod,iterStat : ${prods}"  

其中iterStat可以獲取到狀態(tài)屬性,如iterStat.index 獲取迭代下標(biāo)(0,1,2...)
iterStat 也可不寫,像th:each="prod : ${prods}" 不寫的話默認(rèn)是別名加Stat,如:prodStat。

用模板拼湊頁面

maven 引入

        <dependency>
            <groupId>nz.net.ultraq.thymeleaf</groupId>
            <artifactId>thymeleaf-layout-dialect</artifactId>
            <version>2.2.2</version>
        </dependency>

1.外部頁面引入頁面

//底部
<html xmlns:th="http://www.thymeleaf.org">

<div th:fragment="footer" id="footer" class="clear">
    <p>Copyright ? 2017</p>
</div>

</html>



//頁面想要引用底部
<div th:replace ="layouts/template/footer :: footer"></div>


2.內(nèi)部頁面引入外部頁面

//內(nèi)部頁面
<html xmlns:th="http://www.thymeleaf.org"
      xmlns:layout="http://www.ultraq.net.nz/web/thymeleaf/layout"
      layout:decorator="layouts/table-template">//要引入的外部界面的路徑


    <div layout:fragment="content">
            ...
            內(nèi)容
            ...
    </div>
</html>

//要引入的外部界面
//<!DOCTYPE html>(如果用了h5的聲明就有可能出現(xiàn)樣式問題)
<html xmlns:th="http://www.thymeleaf.org"
      xmlns:layout="http://www.ultraq.net.nz/web/thymeleaf/layout">
      
       <div layout:fragment="content"></div> //上面的內(nèi)容就會出現(xiàn)在這里
      
</html>


語法表

1.基本語法

語法 功能介紹 實例
th:attr 給標(biāo)簽的屬性賦值 <div th:attr="id='666',value='999'">
th:id 替換id <input th:id="'xxx' + ${collect.id}"/>
th:text 文本替換 <p th:text="${collect.description}">description</p>
th:utext 支持html的文本替換 <p th:utext="${htmlcontent}">conten</p>
th:object 替換對象 <div th:object="${session.user}">
th:value 屬性賦值 <input th:value="${user.name}" />
th:with 變量賦值運算 <div th:with="isEven=${prodStat.count}%2==0"></div>
th:style 設(shè)置樣式 th:style="'display: ' + (@{(${sitrue} ? 'none' : 'inline- block')} + ' '"
th:onclick 點擊事件 th:onclick=" 'getCollect()'"
th:each 循環(huán) <tr th:each="item:${list}">
th:if 判斷條件 <a th:if="${userld == collect.userid}" >
th:unless 和th:if判斷相反 <a th:href="@{/login}" th:unless=${session.user != null}>Login</a>
th:href 鏈接地址 <a th:href="@{/login}" th:unless=${session.user != null}>Login</a> />
th:switch 多路選擇配合th:case 使用 被指定為默認(rèn)選項用th:case="*";相當(dāng)于default <div th:switch="${user.role}">
th:case th:switch的一個分支 <p th:case="'admin'">User is an administrator</p>
th:fragment 布局標(biāo)簽,定義可引用的代碼片段 <div th:fragment="alert">
th:include 布局標(biāo)簽,替換內(nèi)容到引入的文件 <head th:include="layout :: htmlhead" th:with="title='xx'"></head> />
th:replace 布局標(biāo)簽,替換整個標(biāo)簽到引入的文件 <div th:replace="fragments/header :: title"></div>
th:selected selected選擇框選中 th:selected="({xxx.id} =={configObj.dd})"
th:src 圖片類地址引入 <img class="img-responsive" alt="App Logo" th:src="@{/img/logo.png}" />
th:inline 定義js腳本可以使用變量 <script type="text/javascript" th: inline="javascript">
th:action 表單提交的地址 <form action="subscribe.html" th:action="@{/subscribe}">
table遍歷 <tr th:each="item:{list}"><br>\<td th:text="{item.tName}"></td>
<td th:text="{item.tAge}">\</td><br>\<td th:text="{item.tAddress}"></td>
</tr>
下拉菜單遍歷 <select class="name">
<option>請選擇</option>
<option th:each="item:{list}" th:value="{item.tId}" th:text="${item.tName}" >
</option>
</select>
日期格式化 <span th:text="${#dates.format(date,'yyyy-MM-dd hh:mm:ss')}">></span>
三目運算符 <td th:text="${name=='zs'}? 張三 : zs"></td>
gt 大于(>)
ge 大于等于(>=)
eq 等于(==)
lt 小于(<)
le 小于等于(<=)
ne 不等于(!=)

2.內(nèi)置對象常用語法

作用 實例 說明
日期格式化 <span th:text="${#dates.format(curDate, 'yyyy-MM-dd HH:mm:ss')}"></span> 使用內(nèi)置對象dates的format函數(shù)即可對日期進行格式化,在format函數(shù)中,第一個參數(shù)是日期對象,對二兩個參數(shù)為日期格式(規(guī)則跟SimpleDateFormat一樣)
數(shù)字格式化 <span th:text="${#numbers.formatDecimal(money, 0, 2)}"></span> 此示例表示保留兩位小數(shù)位,整數(shù)位自動
<span th:text="${#numbers.formatDecimal(money, 3, 2)}"></span> 此示例表示保留兩位小數(shù)位,3位整數(shù)位(不夠的前加0)
獲取列表長度 <span th:text="${#lists.size(datas)}"></span> 使用#lists.size來獲取List的長度。
獲取URL參數(shù)值 <span th:text="${#httpServletRequest.getParameter('page')}"></span> 當(dāng)訪問http://localhost:1105/index?page=5時頁面將會得到page對應(yīng)的值:5
定義變量 <div th:with="curPage={#httpServletRequest.getParameter('page')}"><br>\<h3>當(dāng)前頁碼:\<span th:text="{curPage}"></span></h3>
</div>
當(dāng)訪問http://localhost:1105/index?page=5時,頁面將顯示:當(dāng)前頁碼:5,說明用th:with來定義變量,多個用,號隔開,使用范圍在當(dāng)前標(biāo)簽內(nèi)。
自定義標(biāo)簽屬性 <span th:attr="myDate={#dates.format(curDate, 'yyyy-MM-dd')},myMoney={money}"></span> 在頁面上查看源代碼可以看到:<span myMoney="91.6059494319957" myDate="2016-31-02"></span>,說明自定義屬性用:th:attr,多個屬性用,隔開。

3.字符串操作

作用 實例
判斷是否為空 {#strings.isEmpty(name)}<br>{#strings.arrayIsEmpty(nameArr)}
{#strings.listIsEmpty(nameList)}<br>{#strings.setIsEmpty(nameSet)}
是否包含 {#strings.contains(name,'ez')}<br>{#strings.containsIgnoreCase(name,'ez')}
以xx開始,以xx結(jié)束 {#strings.startsWith(name,'Don')}<br>{#strings.endsWith(name,endingFragment)}
{#strings.indexOf(name,frag)}<br>{#strings.substring(name,3,5)}
{#strings.substringAfter(name,prefix)}<br>{#strings.substringBefore(name,suffix)}
${#strings.replace(name,'las','ler')}
去空格 ${#strings.trim(str)}
獲取長度 ${#strings.length(str)}
是否相等 ${#strings.equals(str)}
字符串轉(zhuǎn)int(轉(zhuǎn)成3位) {#numbers.formatInteger(num, 3)<br>//判斷大于4<br>th:if="{#numbers.formatInteger( num, 3) > #numbers.formatInteger('4',3) }"

踩過的坑

(1)路徑要從templates下算起

(2)背景圖片的添加

<li th:attr="style='background:url('+ @{/images/login_bg2.jpg} + ');background-size:cover;background-color: #074B7B;background-size: 100%;'">

(3)iframe內(nèi)嵌頁面height值太小導(dǎo)致的頁面偏窄

解決辦法:刪除掉最外層頁面的h5聲明<!DOCTYPE html>

(4)引入spring security,

要先在maven中引入

 <dependency>
     <groupId>org.thymeleaf.extras</groupId>
     <artifactId>thymeleaf-extras-springsecurity4</artifactId>
 </dependency>

顯示用戶信息

<span th:text="${#authentication.principal.username}"> 管理員</span>

根據(jù)角色判別,==注意角色名必須要是以“ROLE_”開頭,要不然識別不了==

<div th:if="${#authorization.expression('hasRole(''ROLE_ADMIN'')')}">
    管理員可見
</div>

<div th:if="${#authorization.expression('hasRole(''ROLE_BANK'')')}">
    銀行賬戶可見
</div>

獲取url上面的參數(shù),如 /login?error

<div class="layui-form-item" th:if="${#httpServletRequest.getParameter('error')} " style="color: red;text-align: center">賬號或密碼不正確</div>

(5) 模板中標(biāo)簽必須要有結(jié)束符的解決辦法

在application.yml添加

//使用非嚴(yán)格的html5標(biāo)簽
spring.thymeleaf.mode=LEGACYHTML5

maven 添加依賴

<dependency>
    <groupId>net.sourceforge.nekohtml</groupId>
    <artifactId>nekohtml</artifactId>
    <version>1.9.22</version>
</dependency>

(6) 拼接倆個參數(shù)的類容,其中有null時的處理辦法

//在三目運算外加()
th:text="(${item?.description eq null}?'': ${item?.description})  +${item?.phone}"

(7)獲取動態(tài)字段的值,里面嵌入

//需要在外部  打雙下滑線   __${}__ 預(yù)編譯
//如:${projectData.__${child.name}__}
 <th:block th:each="child:${group.children}">
        <tr>
            <td style="border:0" class="s-dm-title" th:text="${child.label}">

            </td>
            <td style="border:0" class="s-dm-content" th:text="${projectData.__${child.name}__}">

            </td>

        </tr>
        </th:block>
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容