Thymeleaf模板引擎用法總結


Thymeleaf 基本用法總結

一、引用命名空間 <html xmlns:th="http://www.thymeleaf.org"> 

        在html中引入此命名空間,可避免編輯器出現html驗證錯誤,雖然加不加命名空間對Thymeleaf的功能沒有任何影響。

 

二、輸出內容

        2.1  <p th:text="#{home.welcome}">Welcome to our grocery store!</p>

        說明:

                 1. th:text  用來將內容輸出到所在標簽的body中。

                 2. #{home.welcome} 用來引入數據home對象中的 welcome屬性。

                 3. 可以用th:utext 用來顯示“unescaped ” 的html內容。

        2.2    <p>Today is: <span th:text="${today}">13 February 2011</span></p>

        說明:${today} 用來引用 today 變量

三、訪問對象      

       ${param.x} 返回名為x 的 request參數。(可能有多個值)

       ${session.x} 返回名為x的Session參數。

       ${application.x} 返回名為 servlet context 的參數。

     

四、基本語法

       4.1  #{home.welcome} --  訪問數據

       4.2  #{home.welcome(${session.user.name})}  -- 格式化數據 當 home.welcome 為 "abcdegf{0}"  類似這種內容時。(多個參數以逗句分隔)。

       4.3  ${today} --- 訪問變量

       4.4  訪問基本對象

#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.

其它公共對象參考: http://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#appendix-a-expression-basic-objects

        4.5  日期的輸出

        <span th:text="${#calendars.format(today,'dd MMMM yyyy')}">13 May 2011</span>

        4.6  星號語法

<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>

4.7  輸出URL

       <a href="product/list.html" th:href="@{/product/list}">Product List</a>

       <a href="details.html" th:href="@{/order/{orderId}/details(orderId=${o.id})}">view</a>

       4.8  使用代碼段

       <div th:insert="~{commons :: main}">...</div>

       4.9  直接輸出內容   

<span th:text="'working web application'"> -- 輸出字符

<span th:text="2013 + 2">  -- 輸出數據表達式

<div th:if="${user.isAdmin()} == false">  --輸出布爾表達式

<span th:text="'Welcome to our application, ' + ${user.name} + '!'"> -- 帶變量的

4.10 條件表達式

<tr th:class="${row.even}? 'even' : 'odd'">
...  
</tr>

<tr th:class="${row.even}? 'alt'">
...省略 false 結果的表達方式
</tr>

<div th:object="${session.user}">
...省略 true 結果的表達方式
<p>Age: <span th:text="*{age}?: '(no age specified)'">27</span>.</p>
</div>

<span th:text="${user.name} ?: _">no user authenticated</span> --不做任何處理時用下划線 _ 表示

4.11  格式化 

       <td th:text="${{user.lastAccessDate}}">...</td> --${{.}}  調用默認的格式化器來輸出結果。

       4.12  預處理

       <p th:text="${__#{article.text('textVar')}__}">Some text here...</p>  

       說明:thymeleaf 的處理模板內容的順序與書寫順序無關,只能通過  __${expression}__ ,來將需要先一步計算出來后面          要用的變量指定為優化處理。

 

 五、設置 Attribute 值

       5.1 設置任何Attribute 的方法

       <input type="submit" value="Subscribe!" th:attr="value=#{subscribe.submit}"/>   --設置單個

       <img src="../../images/gtvglogo.png"  th:attr="src=@{/images/gtvglogo.png},title=#{logo},alt=#{logo}" />  --一次設置多個

        5.2 設置一些內置的Attribute的方法   

       <li><a href="product/list.html" th:href="@{/product/list}">Product List</a></li>

       <form action="subscribe.html" th:action="@{/subscribe}">

       <input type="submit" value="Subscribe!" th:value="#{subscribe.submit}"/>

       <img src="../../images/gtvglogo.png"  th:src="@{/images/gtvglogo.png}" th:alt-title="#{logo}" /> -- 一次設置多個(alt title)的方法

       其它的可用屬性:http://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#setting-value-to-specific-attributes

        5.3 設置html里沒有指的任何屬性的語法

        <span th:whatever="${user.name}">...</span>   ---whatever 可以換成任何你想設的屬性

 

六、循環輸出的語法

       6.1 基本循環

<tr th:each="prod : ${prods}">

     <td th:text="${prod.name}">Onions</td>
     <td th:text="${prod.price}">2.41</td>
     <td th:text="${prod.inStock}? #{true} : #{false}">yes</td>
</tr>

6.2 循環狀態的使用

<table>
<tr>
<th>NAME</th>
<th>PRICE</th>
<th>IN STOCK</th>
</tr>
<tr th:each="prod,iterStat : ${prods}" th:class="${iterStat.odd}? 'odd'">
<td th:text="${prod.name}">Onions</td>
<td th:text="${prod.price}">2.41</td>
<td th:text="${prod.inStock}? #{true} : #{false}">yes</td>
</tr>
</table>

       關於狀態的其它信息的使用詳細參考:http://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#keeping-iteration-status

       

七、條件判斷

       7.1 if 和 unless

       <a href="comments.html" th:href="@{/comments(prodId=${prod.id})}" th:unless="${#lists.isEmpty(prod.comments)}">view</a>

       <a href="comments.html"  th:href="@{/product/comments(prodId=${prod.id})}"   th:if="${not #lists.isEmpty(prod.comments)}">view</a>

       7.2 switch 語句

<div th:switch="${user.role}">
<p th:case="'admin'">User is an administrator</p>
<p th:case="#{roles.manager}">User is a manager</p>
<p th:case="*">User is some other thing</p>    --默認的 case 相當於default
</div>

 

八、模板 include

      8.1 定義和引用代碼塊

      定義代碼塊

<!DOCTYPE html>

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

<body>

<div th:fragment="copy">
&copy; 2011 The Good Thymes Virtual Grocery
</div>

</body>

</html>

引用代碼塊

<body>

...

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

</body>

引用未用fragment 標注的代碼塊 

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

<body>

...

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

</body>

8.2 th:insert th:replace th:include 之間的區別

th:insert  --- 插入代碼塊    th:replace -- 替換代碼塊會替換掉容器標簽   th:include ---- 和insert相似但只會插入fragment標注body內的內容。

8.3  帶參數的代碼段

<div th:fragment="frag (onevar,twovar)">
<p th:text="${onevar} + ' - ' + ${twovar}">...</p>
</div>

     <div th:replace="::frag (${value1},${value2})">...</div>
     <div th:replace="::frag (onevar=${value1},twovar=${value2})">...</div>

 

九、局部變量的使用示例

<div th:with="firstPer=${persons[0]}">
<p>
The name of the first person is <span th:text="${firstPer.name}">Julius Caesar</span>.
</p>
</div>

<div th:with="firstPer=${persons[0]},secondPer=${persons[1]}">
<p>
The name of the first person is <span th:text="${firstPer.name}">Julius Caesar</span>.
</p>
<p>
But the name of the second person is
<span th:text="${secondPer.name}">Marcus Antonius</span>.
</p>
</div>

十、注釋

        <!-- ... -->  

十一、說明

        以上只列出Thymeleaf了簡要常用的語法和使用方式,更多詳情的說明和規則請參見:http://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#introducing-thymeleaf

基於Spring Boot的Thymeleaf使用

SpringBoot中默認不在支持JSP頁面,但它引入了模板框架的使用。我們可以使用模板框架對頁面中的內容進行動態綁定

Thymeleaf:一個服務端Java模板引擎,類似於JSP。它為網頁的開發工作流程帶來優雅的靜態模板,它同時可以靜態原型來使用。

JSP本質上是Servlet的前端改版,JSP文件在服務器啟動時會被轉化為一個Servlet來運行,而這個轉換過程的效率是十分低的。

Thymeleaf不同於JSP的是它是在HTML文件上進行工作的,我們的模板可以單獨作為HTML靜態文件運行。模板的外觀和功能上依舊類似於HTML,並且模板語法可以被瀏覽器正確的顯示。

引入Thymeleaf
簡單的例子:

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
 <head>
 <title>Welcome Page</title>
 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
 </head>
 <body>
 <span th:text="${message}">Welcome to Thymeleaf!</span>
 </body>
 </body>
</html>

不同於原生靜態頁面,xmlns:th="http://www.thymeleaf.org"並不會對模板頁面的生成啟任何作用,主要是引入命名空間使得IDE不會對我們的模板語法報錯;th:text="${message}為模板語法,用於替換標簽所在的文本信息(如果${message}可以取出有效值)

SpringBoot默認是支持Thymeleaf的,我們只需要導入對應的jar包即可:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

如果SpringBoot默認指定的版本不符合我們的需求,我們可以在properties標簽中覆蓋SpringBoot指定的版本號。具體標簽寫法可以參考spring-boot-starter-parent的父pomspring-boot-dependencies

導入對應的依賴后,SpringBoot將自動裝配模板。並且部分屬性配置如下:

@ConfigurationProperties(prefix = "spring.thymeleaf")
public class ThymeleafProperties {

	private static final Charset DEFAULT_ENCODING = StandardCharsets.UTF_8;

	public static final String DEFAULT_PREFIX = "classpath:/templates/";

	public static final String DEFAULT_SUFFIX = ".html";
}

我們可以知道模板默認支持.html文件,在我們控制器中進行跳轉時只需返回模板名即可(類似於InternalResourceViewResolver)。並且我們默認以UTF-8編碼解析模板

Thymeleaf語法
表達式
Thymeleaf支持多種表達式,如:

變量表達式${...}
選擇變量表達式*{...}
鏈接表達式@{...}
消息表達式#{...}
代碼表達式~{...}
${...}等同於OGNL語法,用於從上下文查找指定的值。如獲取對象中的屬性、調用對象的方法:

/*
* 使用(.)分割屬性的層級,獲取將調用屬性的getter方法
*/
${person.father.name}
/*
* 還可以通過([])的方式獲取屬性
*/
${person['father']['name']}
/*
* 如果對象是一個map,則點和括號都可以調用map的get(Object key)方法
*/
${countriesByCode.ES}
${personsByName['Stephen Zucchini'].age}
/*
* 如果對象是一個數組,我們可以直接使用在Java中的調用方式
*/
${personsArray[0].name}
/*
* 表達式也可以調用對象的方法,方法可以傳入參數
*/
${person.createCompleteName()}
${person.createCompleteNameWithSeparator('-')}

OGNL也提供一些基本的表達式對象,我們可以直接使用#符號引用:

#ctx:上下文對象
#vars:上下文對象
#locale:上下文區域設置
#request:(僅在Web Contexts中)HttpServletRequest對象
#response:(僅在Web上下文中)HttpServletResponse對象
#session:(僅在Web上下文中)HttpSession對象
#servletContext:(僅在Web上下文中)ServletContext對象

我們可以這樣得到一些變量:

local country:<span th:text="${#locale.country}">US</span>

實例補充:https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#appendix-a-expression-basic-objects

除此之外,OGNL還提供了一組工具對象供我們快速完成常見任務:

#execInfo:有關正在處理的模板謝謝
#message:用於在變量表達式中獲取外部化消息的方法,與使用#語法獲得的方式相同
#uris:轉義URL/URI部分的方法
#conversions:執行配置的轉換服務(如果有的話)的方法
#dates:java.util.Date對象的方法:格式化,組件提取等
#calendars:類似於#dates,但對於java.util.Calendar對象
#numbers:用於格式化數字對象的方法
#strings:String對象的方法:contains,startsWith,prepending/appending等
#objects:一般對象的方法
#bools:布爾評估的方法
#arrays:數組的方法
#lists:列表的方法
#sets:集合的方法
#maps:map的方法
#aggregates:在數組或集合上創建聚合的方法
#ids:處理可能重復的id屬性的方法(例如:作為迭代的結果)

*{...}大部分功能和${}是一致的,它只是作了一些補充功能:

<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>

當我們在標簽中使用th:object獲取指定對象時,此時標簽內*{}默認選定指定的對象。我們可以直接通過屬性名獲取值

@{...}用來鏈接項目中的API,如:

<a href="details.html" th:href="@{http://localhost:8080/gtvg/order/details(orderId=${o.id})}">view</a>
<!-- 我們也可以使用項目的相對路徑 -->
<a href="details.html" th:href="@{/order/details(orderId=${o.id})}">view</a>

參數用()包圍,多個參數用,隔開

{...}可以用於在國際化中顯示消息,也可以使用內置對象

~{...}用來插入片段文檔,如:

<div th:insert="~{commons :: main}">...</div>

文本

字符串:'one text' , 'another one' , ...
數字:0 , 34 ...
布爾值:true , false ...
空:null
文字標記:one,sometext ...
文本操作

字符串拼接:+
字符替換:|The name is $|
計算操作

二元操作:+ , - , * , / , %
一元操作(負號):-
布爾操作

二元操作:and , or
布爾反轉:! , not
比較操作

比較操作:> , < , >= , <= ( gt , lt , ge , le)
判同操作:== , != (eq , ne)
條件操作

if-then:(if) ? (then)
if-then-else:(if) ? (then) : (else)
default:(value) ?: (defalutvalue)

以上的各種操作都是在對html標簽屬性值的計算。如果我們需要操作html結構,我們需要使用th:*對html文件結構進行操作

Thymeleaf操作
判斷操作

<!-- 當表達式成立,該span標簽才會顯示 -->
<span th:if="判斷表達式">1</span>
<!-- 當表達式不成立時,才會顯示。與th:if表達式相同,形成if-else -->
<span th:unless="判斷表達式">2</span>

模板導入

將代碼中重復的代碼抽離出來,成為模板文件。我們即可在其他需要使用模板文件的地方引入即可

如:底部模板文件footer.html

<!DOCTYPE html>
<html xmlns:th="http://www.w3.org/1999/xhtml">
<body>
<!-- th:fragment指定模板名稱,以便調用 -->
<div th:fragment="footer">
    <!-- 模板文件結構 -->
</div>
</body>
</html>

當我們在其他文件需要使用到模板結構時,我們可以引入即可

<div th:include="footer::footer"></div>

::前面的footer表示模板所在的文件路徑,::后面的footer表示我們在模板文件中指定的模板名稱

模板的文件路徑也是由Thymeleaf的視圖解析器進行解析的,所以默認的路徑為classpath:templates/xxx.html

引入模板有以下三種方式:

th:insert:模板片段插入th:insert所在標簽內
th:replace:模板片段替換th:replace所在的標簽
th:include:模板片段中的內容插入th:include所在的標簽內
模板例子:

<footer th:fragment="copy">  &copy; 2011 The Good Thymes Virtual Grocery </footer>

使用三種方式引入模板:

<div th:insert="footer :: copy"></div>
<div th:replace="footer :: copy"></div>
<div th:include="footer :: copy"></div

結果為:

<div>
    <footer>
        &copy; 2011 The Good Thymes Virtual Grocery
    </footer>
</div>
	<footer>
      &copy; 2011 The Good Thymes Virtual Grocery
	</footer>
<div>
	&copy; 2011 The Good Thymes Virtual Grocery
</div> 

模板在使用的時候是可以傳入參數的,可以根據參數模板有不同的顯示狀態

模板傳值:

<footer th:fragment="copy(name)"> [[name]]  &copy; 2011 The Good Thymes Virtual Grocery </footer>

使用時:

<div th:insert="footer :: copy(name='zxj')"></div>

文本輸出

用來將文本輸出到所在標簽的內部,而不是屬性中

有兩種方法輸出:

<span th:text="${msg}"></span>

或者

<span th:utext="{msg}"></span>

區別:

兩者同樣是講標簽中的文本替換,th:text會將替換文本中的特殊字符轉義,如hello會渲染成粗體。但th:utext會把替換文本中的字符按原樣輸出,不會轉義

上面兩種都屬於標簽內寫法,它也有行內寫法。如:

<p>Hello,[[${session.user.name}]]</p>

[[]]等同於th:text,或者

<p>The message is "[(${msg})]"</p>

等同於th:utext

塊區域操作

th:block是Thymeleaf唯一一個操作結構塊的標簽,假設我們有下面一個例子:

<table>
  <div th:each="user : ${users}">
    <tr>
        <td th:text="${user.login}">...</td>
        <td th:text="${user.name}">...</td>
    </tr>
    <tr>
        <td colspan="2" th:text="${user.address}">...</td>
    </tr>
  </div>
</table>

這表示我們將迭代顯示div中的內容,但是div的存在對結構有着一定的影響。我們需要迭代多個標簽,但是我們又不想添加額外的外層結構。

我們可以使用th:block進行迭代,如:

<table>
  <th:block th:each="user : ${users}">
    <tr>
        <td th:text="${user.login}">...</td>
        <td th:text="${user.name}">...</td>
    </tr>
    <tr>
        <td colspan="2" th:text="${user.address}">...</td>
    </tr>
  </th:block>
</table>

使用這種方式,th:block標簽會在迭代完后直接消失的。只會保留標簽內部的內容,非常適合迭代多個標簽並不添加額外的外層結構

常用的操作

順序 特點 屬性
1 導入模板代碼 th:insert、th:replace
2 集合迭代 th:each
3 流程控制 th:if、th:unless、th:switch、th:case
4 本地變量定義 th:object、th:with
5 常規屬性修改 th:attr、th:attrprepend、th:attrappend
6 特定屬性修改 th:value、th:href、th:src 、...
7 標簽內文本修改 th:text、th:utext
8 模板代碼定義 th:fragment
9 模板移除 th:remove

出處來自https://heartdream.top/archives/2020020701252332414


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM