Thymeleaf 模板引擎簡介


目錄

Thymeleaf 模板引擎

官方文檔下載

Hello World

新建應用

后台控制器

前端頁面

瀏覽器訪問測試

Thymeleaf 模板引擎
1、Thymeleaf 是 Web 和獨立環境的現代服務器端 Java 模板引擎,能夠處理HTML,XML,JavaScript,CSS 甚至純文本。

2、Thymeleaf 的主要目標是提供一種優雅和高度可維護的創建模板的方式。為了實現這一點,它建立在自然模板的概念上,將其邏輯注入到模板文件中,不會影響模板被用作設計原型。這改善了設計的溝通,彌補了設計和開發團隊之間的差距。

3、Thymeleaf 也從一開始就設計了Web標准 - 特別是 HTML5 - 允許您創建完全驗證的模板,Spring Boot 官方推薦使用  thymeleaf 而不是 JSP。

4、Thymeleaf 官網:https://www.thymeleaf.org/

5、Thymeleaf 在 Github 的主頁:https://github.com/thymeleaf/thymeleaf

6、Spring Boot 中使用 Thymeleaf  模板引擎時非常簡單,因為 Spring Boot 已經提供了默認的配置,比如解析的文件前綴,文件后綴,文件編碼,緩存等等,程序員需要的只是寫 html 中的內容即可,可以參考《Spring Boot 引入 Thymeleaf 及入門》

模板引擎

1)市面上主流的 Java 模板引擎有:JSP、Velocity、Freemarker、Thymeleaf

2)JSP本質也是模板引擎,Spring Boot 官方推薦使用 “Thymeleaf”模板引擎

3)模板引擎原理圖如下,模板引擎的作用都是將模板(頁面)和數據進行整合然后輸出顯示,區別在於不同的模板使用不同的語法,如 JSP 的 JSTL 表達式,以及 JSP 自己的表達式和語法,同理 Thymeleaf 也有自己的語法

Hello World

1、直接使用 Spring Boot 應用來學習 Thymeleaf所有語法知識,下面第一步就是新建 Spring Boot 項目,對於Spring Boot 不熟悉的可以參考《Spring Boot》

<!-- 導入Spring Boot的thymeleaf依賴-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

2、上面的配置同樣在 Spring Boot官方文檔 中也可以找到

后台控制器
package com.lct.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.Map;

/**
* Created by Administrator on 2018/7/17 0017.
* 用戶控制器
*/
@Controller
public class UserController {

/**
* 全部基於 Spring Boot給 Thymeleaf的默認配置
* 所以下面會跳轉到 classpath:/templates/home.html 頁面
*
* @param paramMap
* @return
*/
@RequestMapping("home")
public String goHome(Map<String, Object> paramMap) {
/** 默認Map的內容會放大請求域中,頁面可以直接使用Thymeleaf取值*/
paramMap.put("name", "張三");
paramMap.put("age", 35);
return "home";
}

}
前端頁面
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>主頁</title>
</head>
<body>
<h3>歡迎來到主頁</h3>
<!--Thymeleaf 語法取值-->
姓名:<span th:text="${name}">未知</span>
年齡:<span th:text="${age}">未知</span>
</body>
</html>

 

1、對於Spring Boot關於 Thymeleaf 的渲染規則不清楚的,可以參考《Spring Boot 引入 Thymeleaf 及入門》

2、關於 Thmeleaf 的更多深入內容可以參考《Thymeleaf》

 

參考:https://blog.csdn.net/wangmx1993328/article/details/81054474


免責聲明!

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



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