Thymeleaf模板引擎
- 我記得之前寫過,今天才發現把這個給落下了,代碼都沒了,找了個例子,記錄下來
- 實際上,現在企業級應用開發,前後端分離越來越多。但是總有老項目,甚至於還要維護骨灰級代碼。
- 模板引擎有很多,引用方式基本上一致。
Thymeleaf簡介
-
Thymeleaf是適用於Web和獨立環境的現代服務器端Java模板引擎。
-
Thymeleaf的主要目標是爲您的開發工作流程帶來優雅的自然模板 -HTML可以在瀏覽器中正確顯示,也可以作爲靜態原型工作,從而可以在開發團隊中加強協作。
-
Thymeleaf擁有適用於Spring Framework的模塊,與您喜歡的工具的大量集成以及插入您自己的功能的能力,對於現代HTML5 JVM Web開發而言,Thymeleaf是理想的選擇-儘管它還有很多工作要做。
-
要注意的是thymeleaf不是spring旗下的。
-
自然模板
<table>
<thead>
<tr>
<th th:text="#{msgs.headers.name}">Name</th>
<th th:text="#{msgs.headers.price}">Price</th>
</tr>
</thead>
<tbody>
<tr th:each="prod: ${allProducts}">
<td th:text="${prod.name}">Oranges</td>
<td th:text="${#numbers.formatDecimal(prod.price, 1, 2)}">0.99</td>
</tr>
</tbody>
</table>
- 基本語法可以看一下這位仁兄的博客Thymeleaf的基本語法
- 這位更全面,評論6樓有驚喜 Thymeleaf入門到吃灰
在springboot中使用Themeleaf模板
1.添加依賴
- 在pom.xml中添加依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
2.配置Themeleaf
- Spring Boot爲Thymeleaf提供了自動化配置類。也就是說可以使用默認配置。
- 作爲開發者,對默認的配置進行修改,只需要在application.properties/application.yml中進行配置。
#是否開啓緩存,開發時可設置爲false,默認爲true
spring.thymeleaf.cache=true
#是否檢查模板是否存在,默認爲true
spring.thymeleaf.check-template=true
#是否檢查模板位置是否存在,默認爲true
spring.thymeleaf.check-template-location=true
#模板文件編碼
spring.thymeleaf.encoding=UTF-8
#模板文件位置
spring.thymeleaf.prefix=classpath:/templates/
#Content-Type配置
spring.thymeleaf.servlet.content-type=text/html
#模板文件後綴
spring.thymeleaf.suffix=.html
3.創建實體類
public class Book {
private Integer id;
private String name;
private String author;
//省略getter/setter
}
4.創建控制類
- 在Controller中返回ModelAndView
@Controller
public class BookController {
@GetMapping("/books")
public ModelAndView books() {
List<Book> books = new ArrayList<>();
Book b1 = new Book();
b1.setId(1);
b1.setAuthor("羅貫中");
b1.setName("三國演義");
Book b2 = new Book();
b2.setId(2);
b2.setAuthor("曹雪芹");
b2.setName("紅樓夢");
books.add(b1);
books.add(b2);
ModelAndView mv = new ModelAndView();
mv.addObject("books", books);
mv.setViewName("books");
return mv;
}
}
5.創建承載頁面
- 在resource目錄下的templates目錄中創建books.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>圖書列表</title>
</head>
<body>
<table border="1">
<tr>
<td>圖書編號</td>
<td>圖書名稱</td>
<td>圖書作者</td>
</tr>
<tr th:each="book:${books}">
<td th:text="${book.id}"></td>
<td th:text="${book.name}"></td>
<td th:text="${book.author}"></td>
</tr>
</table>
</body>
</html>
6.運行程序
- 在瀏覽器中輸入“http://localhost:8080/books”,即可看到運行效果
- 歡迎大家關注我的公衆號