Thymeleaf 搜索模板引擎

1.Thymeleaf是什麼?

Thymeleaf是一種用於Web和獨立環境的現代服務器端的Java模板引擎。html

Thymeleaf的主要目標是將優雅的天然模板帶到開發工做流程中,並將HTML在瀏覽器中正確顯示,而且能夠做爲靜態原型,讓開發團隊能更容易地協做。Thymeleaf可以處理HTML,XML,JavaScript,CSS甚至純文本。前端

Thymeleaf使用Spring框架的模塊,與許多常見的工具集成在一塊兒,而且能夠插入本身的功能,是現代HTML5 JVM Web開發的理想選擇,儘管Thymeleaf還有更多其它的功能。
Thymeleaf創建在天然模板的概念之上,以不影響模板做爲設計原型的方式將其邏輯注入到模板文件中。 這改善了設計溝通,彌合了前端設計和開發人員之間的理解誤差。html5

Spring Boot提供了默認配置的模板引擎主要有如下幾種:程序員

  • Thymeleaf
  • FreeMarker
  • Velocity
  • Groovy
  • Mustache

Spring Boot建議使用這些模板引擎,避免使用JSP,若必定要使用JSP將沒法實現Spring Boot的多種特性,須要進行配置。spring

 

2.Thymeleaf的特色

(1)Thymeleaf 在有網絡和無網絡的環境下皆可運行,即它可讓美工在瀏覽器查看頁面的靜態效果,也可讓程序員在服務器查看帶數據的動態頁面效果。這是因爲它支持 html 原型,而後在 html 標籤裏增長額外的屬性來達到模板+數據的展現方式,這些標籤屬性就會在DOM(文檔對象模型)上執行預先制定好的邏輯。瀏覽器解釋 html 時會忽略未定義的標籤屬性,因此 thymeleaf 的模板能夠靜態地運行;當有數據返回到頁面時,Thymeleaf 標籤會動態地替換掉靜態內容,使頁面動態顯示。後端

(2)Thymeleaf 開箱即用的特性。它提供標準和spring標準兩種方言,能夠直接套用模板實現JSTL、 OGNL表達式效果,避免天天套模板、改jstl、改標籤的困擾。同時開發人員也能夠擴展和建立自定義的方言。瀏覽器

(3)Thymeleaf 提供spring標準方言和一個與 SpringMVC 完美集成的可選模塊,能夠快速的實現表單綁定、屬性編輯器、國際化等功能。緩存

3.引入依賴

在Spring Boot中使用Thymeleaf,只須要引入下面依賴,並在默認的模板路徑src/main/resources/templates下編寫模板文件便可完成。springboot

 

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

 

非springboot項目使用以下依賴:服務器

<dependency>
    <groupId>org.thymeleaf</groupId>
    <artifactId>thymeleaf</artifactId>
    <version>2.1.4</version>
</dependency>

 

4.配置Thymeleaf的視圖解析器

#thymeleaf start

#使用html5標準 spring.thymeleaf.mode
=HTML5
spring.thymeleaf.encoding
=UTF-8

spring.thymeleaf.content-type=text/html
#開發時關閉緩存,否則無法看到實時頁面 spring.thymeleaf.cache
=false

#thymeleaf end

 

使用html5標準設置後thymeleaf對.html的內容要求很嚴格,實際項目中可能會有不太嚴格的HTML格式,建議增長下面字段:

spring.thymeleaf.mode = LEGACYHTML5


spring.thymeleaf.mode的默認值是HTML5,實際上是一個很嚴格的檢查,改成LEGACYHTML5能夠獲得一個可能更友好親切的格式要求。

須要注意的是,LEGACYHTML5須要搭配一個額外的庫NekoHTML纔可用。

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

 

5.示例——用Thymeleaf渲染一個頁面

(1)Controller類

 1 @RestController
 2 public class HelloController {
 3     public EsBlogRepository esBlogRepository;
 4     @RequestMapping("/blogs")
 5     public String listBlogs(Model model){
 6         //按照文章狀態查詢博文列表
 7         List<EsBlog> blogList = esBlogRepository.findByBlogStatus(1);
 8         //加入屬性,用來在模板中讀取
 9         model.addAttribute("blogs",blogList);
10         //return 模板文件的名稱,對應src/mani/resources/templates/blogs.html
11         return "blogs";
12     }
13 }

 

(2)html5

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8" />
    <title></title>
</head>
<body>
    <div class="card mb-4" th:each="blog : ${blogList}">
        <div class="card-block">
        <h2 class="card-title">
            <span>
            <a href="/u/waylau" title="waylau" th:href="'/u/' + ${blog.username}"  th:title="${blog.username}">
                      <img src="/images/avatar-defualt.jpg" th:src="${blog.avatar} == null ? '/images/avatar-defualt.jpg' : ${blog.avatar}"  class="blog-avatar-50">
            </a>
        </span>
        <a href="/u/waylau/blogs/1" class="card-link" title="waylau" 
                                    th:href="'/u/' + ${blog.username} + '/blogs/'+ ${blog.blogId}"  th:title="${blog.title}" th:text="${blog.title}">
                                    OAuth 2.0 認證的原理與實踐
        </a>
    </h2>
    <p class="card-text" th:text="${blog.summary}">使用 OAuth 2.0 認證的的好處是顯然易見的。你只須要用同一個帳號密碼,就能在各個網站進行訪問,而免去了在每一個網站都進行註冊的繁瑣過程。</p>
    <div class="card-text">
           <a href="/u/waylau" th:href="'/u/' + ${blog.username}" class="card-link" th:text=${blog.username}>waylau</a> 發表於 [[${#dates.format(blog.createTime, 'yyyy-MM-dd HH:mm')}]]
                     <i class="fa fa-eye" aria-hidden="true">[[${blog.readSize}]]</i>
             <i class="fa fa-heart-o" aria-hidden="true">[[${blog.voteSize}]]</i> <i class="fa fa-comment-o"
                                                                                      aria-hidden="true">[[${blog.commentSize}]]</i>
        </div>
    </div>
    </div>
</body>
</html>                        

 

如上頁面,直接打開blogs頁面只顯示《OAuth 2.0 認證的原理與實踐》一篇文章,但當啓動程序後,訪問http://localHost:8080/(能夠自定義),則是顯示Contller種blogList中全部的內容。

 

6.基礎語法,參考:連接

(1)建立html

須要在html中添加:

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

 

這樣,下文才能正確使用th:*形式的標籤

xmlns 屬性能夠在文檔中定義一個或多個可供選擇的命名空間。該屬性能夠放置在文檔內任何元素的開始標籤中。該屬性的值相似於 URL,它定義了一個命名空間,瀏覽器會將此命名空間用於該屬性所在元素內的全部內容。

 

(2)獲取變量值${...}

<p th:text="'Hello!, ' + ${name} + '!'">吃了嗎?</p>

 

(3)選擇變量表達式*{...}

<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> 
等價於
<div>
    <p>Name: <span th:text="${session.user.firstName}">Sebastian</span>.</p> 
    <p>Surname: <span th:text="${session.user.lastName}">Pepper</span>.</p> 
    <p>Nationality: <span th:text="${session.user.nationality}">Saturn</span>.</p>
</div>

 

p裏面的原有的值只是爲了給前端開發時作展現用的.這樣的話很好的作到了先後端分離。

這也是Thymeleaf很是好的一個特性:在無網絡的狀況下也能運行,也就是徹底能夠前端先寫出頁面,模擬數據展示效果,後端人員再拿此模板修改便可。

 

(4)連接表達式: @{…}
用來配合link、src、href使用的語法,相似的標籤有: th:href th:src

<!-- Will produce 'http://localhost:8080/gtvg/order/details?orderId=3' (plus rewriting) --> 

<a href="details.html" th:href="@{http://localhost:8080/gtvg/order/details(orderId=${o.id})}">view</a>
<!-- Will produce '/gtvg/order/details?orderId=3' (plus rewriting) -->

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

<a href="details.html" th:href="@{order/{orderId}/details(orderId=${o.id})}">Content路徑,默認訪問static下的order文件夾</a>

 

(5)文本替換

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

<!-只能包含表達式變量,而不能有條件判斷等->

<span th:text="|Welcome to our application, ${user.name}!|">

 

(6)運算符

數學運算

  • 二元操做:+, - , * , / , %
  • 一元操做: - (負)

邏輯運算

  • 一元 : and or
  • 二元 : !,not

比較運算(爲避免轉義尷尬,可使用括號中的英文進行比較運算!)

  • 比較:> , < , >= , <= ( gt , lt , ge , le )
  • 等於:== , != ( eq , ne )

條件運算

  • If-then: (if) ? (then)
  • If-then-else: (if) ? (then) : (else)
  • Default: (value) ?: (defaultvalue)
'User is of type ' + (${user.isAdmin()} ? 'Administrator' : (${user.type} ?: 'Unknown'))

 

(7)條件

if/unless

   使用 th:if 和 th:unless 屬性進行條件判斷,th:unless 與 th:if 剛好相反,只有表達式中的條件不成立,纔會顯示其內容。

<a th:href="@{/login}" th:unless=${session.user != null}>Login</a>

 

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

 

(8)循環

經過th:each,示例中有使用到。

 

7.經常使用標籤

 

 // 相似於th:object和th:field等進行表單參數綁定仍是頗有用的!使用與注意事項,參見:這裏

 

參考文章:

http://www.javashuo.com/article/p-snzoewsh-ho.html

https://www.e-learn.cn/thymeleaf

 2019-06-07

相關文章
相關標籤/搜索