Thymeleaf介紹及基礎語法

thymeleaf是一個XML/XHTML/HTML5模板引擎,可用於Web與非Web環境中的應用開發。它是一個開源的Java庫,基於Apache License 2.0許可,由Daniel Fernández創建,該作者還是Java加密庫Jasypt的作者。

Thymeleaf提供了一個用於整合Spring MVC的可選模塊,在應用開發中,你可以使用Thymeleaf來完全代替JSP或其他模板引擎,如Velocity、FreeMarker等。Thymeleaf的主要目標在於提供一種可被瀏覽器正確顯示的、格式良好的模板創建方式,因此也可以用作靜態建模。你可以使用它創建經過驗證的XML與HTML模板。相對於編寫邏輯或代碼,開發者只需將標籤屬性添加到模板中即可。接下來,這些標籤屬性就會在DOM(文檔對象模型)上執行預先制定好的邏輯。

它的特點便是:開箱即用,Thymeleaf允許您處理六種模板,每種模板稱爲模板模式:

  • XML

  • 有效的XML

  • XHTML

  • 有效的XHTML

  • HTML5

  • 舊版HTML5

所有這些模式都指的是格式良好的XML文件,但Legacy HTML5模式除外,它允許您處理HTML5文件,其中包含獨立(非關閉)標記,沒有值的標記屬性或不在引號之間寫入的標記屬性。爲了在這種特定模式下處理文件,Thymeleaf將首先執行轉換,將您的文件轉換爲格式良好的XML文件,這些文件仍然是完全有效的HTML5(實際上是創建HTML5代碼的推薦方法)1

另請注意,驗證僅適用於XML和XHTML模板。

然而,這些並不是Thymeleaf可以處理的唯一模板類型,並且用戶始終能夠通過指定在此模式下解析模板的方法和編寫結果的方式來定義他/她自己的模式。這樣,任何可以建模爲DOM樹(無論是否爲XML)的東西都可以被Thymeleaf有效地作爲模板處理。

2.Springboot整合thymeleaf

使用springboot 來集成使用Thymeleaf可以大大減少單純使用thymleaf的代碼量,所以我們接下來使用springboot集成使用thymeleaf.

實現的步驟爲:

  • 創建一個sprinboot項目

  • 添加thymeleaf的起步依賴

  • 添加spring web的起步依賴

  • 編寫html 使用thymleaf的語法獲取變量對應後臺傳遞的值

  • 編寫controller 設置變量的值到model中

(1)創建工程

創建一個獨立的工程springboot-thymeleaf,該工程爲案例工程,不需要放到changgou工程中。

pom.xml依賴

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 <modelVersion>4.0.0</modelVersion>
​
 <groupId>com.itheima</groupId>
 <artifactId>springboot-thymeleaf</artifactId>
 <version>1.0-SNAPSHOT</version>
​
 <parent>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-parent</artifactId>
 <version>2.1.4.RELEASE</version>
 </parent>
​
 <dependencies>
 <!--web起步依賴
 Tomcat 
 Springmvc  引賴Jar包  一箇中心 三大組件
-->
 <dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-web</artifactId>
 </dependency>
​
 <!--thymeleaf配置-->
 <dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-thymeleaf</artifactId>
 </dependency>
 </dependencies>
</project>

(2)創建html

在resources中創建templates目錄,在templates目錄創建 demo1.html,代碼如下:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
 <title>Thymeleaf的入門</title>
 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
</head>
<body>
<!--輸出hello數據-->
<p th:text="${hello}"></p>
</body>
</html>

解釋:

<html xmlns:th="http://www.thymeleaf.org">:這句聲明使用thymeleaf標籤

<p th:text="${hello}"></p>:這句使用 th:text="${變量名}" 表示 使用thymeleaf獲取文本數據,類似於EL表達式。

(3)修改application.yml配置

創建application.yml,並設置thymeleaf的緩存設置,設置爲false。默認加緩存的,用於測試。

spring:
 thymeleaf:
 cache: false

(4)控制層

創建controller用於測試後臺 設置數據到model中。

創建com.itheima.controller.TestController,代碼如下:

@Controller
@RequestMapping("/test")
public class TestController {
​
 /***
 * 訪問/test/hello  跳轉到demo1頁面
 * @param model
 * @return
 */
 @RequestMapping("/hello")
 public String hello(Model model){
 model.addAttribute("hello","hello welcome");
 return "demo1";
 }
}

(5)測試

啓動系統,並在瀏覽器訪問

http://localhost:8080/test/hello

Thymeleaf基本語法

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Thymeleaf的入門</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
</head>
<body>
<!--輸出hello數據-->
<!--<p th:text="${hello}"></p>-->
//直接輸出值
輸出在這裏:[[${hello}]]   [[${session.name}]]

//提交form表單
<form th:action="@{/test/hello}" th:method="get">
    <input th:type="text"  th:name="id" th:value="1111111">
    <button>提交</button>
</form>

遍歷學生list:
<div >
    <ul th:each="user:${users}">
       ID:<li th:text="${user.id}"></li>
       Name:<li th:text="${user.name}"></li>
       地點:<li th:text="${user.address}"></li>
    </ul>
</div>
遍歷Map  Map java  java.keys 遍歷Key 取Value      java.entrySet 遍歷關係  通過關係可以取Key或Value值
<table>
    <tr th:each="map,m:${dataMap}">
        <td th:text="${map}"></td>
        <td th:text="${m.current.key}"></td>
        <td th:text="${m.current.value}"></td>

    </tr>
</table>

//遍歷數組 
<table>
    <tr th:each="n,nm:${names}">
        <td th:text="${nm.count}"></td><td th:text="${n}"></td><td th:text="${nm.index}"></td>
    </tr>
</table>
//日期
<div>
    <span th:text="${#dates.format(now,'yyyy-MM-dd HH:ss:mm')}"></span>
</div>
//判斷
<div>
    <span th:if="${(age>=18)}">終於長大了!</span>
    <span th:unless="${(age>=18)}">沒有長大!</span>
</div>

</body>
th:include

可以直接引入th:fragment,在demo1.html中引入如下代碼:

<div id="A" th:include="footer::copy"></div>

</html>
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta th:fragment="hoho" http-equiv="Content-Type" content="text/html;charset=charset=utf-8">
    <title th:fragment="ttttt">fragment</title>
</head>
<body>
th:fragment 定義一個模塊

可以定義一個獨立的模塊,創建一個footer.html代碼如下

<div id="C" th:fragment="copy" >
    關於我們<br/>
</div>
</body>
</html>

後臺:

package com.thymeleaf.controller;

import com.thymeleaf.pojo.User;
import javafx.scene.input.DataFormat;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.util.*;

/****
 * @Author:lx
 * @Description:
 * @Date 2019/8/24 15:17
 *****/
@Controller
public class ThymeleafController {

    //請求
    @RequestMapping("/hello/demo1")
    public String demo1(Model model, HttpSession session){
        model.addAttribute("hello","世界你好");
        session.setAttribute("name","哈哈");
        return "demo1";
    }
    @RequestMapping("/test/hello")
    public String demo2(String id){

        return "demo1";
    }

    /***
     * 訪問/test/hello  跳轉到demo1頁面
     * @param model
     * @return
     */
    @RequestMapping("/hello")
    public String hello(Model model){
        model.addAttribute("hello","hello welcome");

        //集合數據
        List<User> users = new ArrayList<User>();
        users.add(new User(1,"張三","深圳"));
        users.add(new User(2,"李四","北京"));
        users.add(new User(3,"王五","武漢"));
        model.addAttribute("users",users);


        //Map定義
        Map<String,Object> dataMap = new HashMap<String,Object>();
        dataMap.put("No","123");//No=123
        dataMap.put("address","深圳");


        model.addAttribute("dataMap",dataMap);

        //存儲一個數組
        String[] names = {"張三","李四","王五"};
        model.addAttribute("names",names);


        //日期
        model.addAttribute("now",new Date());//英國的 格林威志時間   --》String類型


        //if條件
        model.addAttribute("age",18);
        return "demo1";
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章