網站首頁 編程語言 正文
Thymeleaf模板引擎
模板引擎的作用就是我們來寫一個頁面模板,比如有些值呢,是動態的,我們寫一些表達式。而這些值,從哪來呢,就是我們在后臺封裝一些數據。然后把這個模板和這個數據交給我們模板引擎,模板引擎按照我們這個數據幫你把這表達式解析、填充到我們指定的位置,然后把這個數據最終生成一個我們想要的內容給我們寫出去,這就是我們這個模板引擎
如果我們沒有模板引擎的話,在頁面中會提示500
引入Thymeleaf
在項目中加入依賴
<!--thymeleaf-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
Thymeleaf 官網:https://www.thymeleaf.org/
Thymeleaf 在Github 的主頁:https://github.com/thymeleaf/thymeleaf
Spring官方文檔:找到我們對應的版本
https://docs.spring.io/spring-boot/docs/2.3.7.RELEASE/reference/htmlsingle/#using-boot-starter
我們可以有通過上述的頁面找到我們需要的依賴,進而復制粘貼即可。
引入之后我們再次運行。nice
注意: 使用Thymeleaf,只需要導入對應的依賴即可。同時我們的html頁面試放在我們的templates目錄下的。
至于為什么,我們看源碼,這段源碼在ThymeleafProperties
下。
private String prefix = "classpath:/templates/";
private String suffix = ".html";
取值
那么我們應該怎么取值呢
首先在controller下編寫代碼
@Controller
public class HelloController {
@RequestMapping("/test")
public String hello(Model model){
model.addAttribute("msg","王木木");
return "test";
}
}
接下來我們在html頁面中編寫
因為我們要使用thymeleaf,需要在html文件中導入命名空間的約束。
<html lang="en" xmlns:th="http://www/thymeleaf.org">
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www/thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div th:text="${msg}"></div>
</body>
</html>
成功運行后
這里需要這個的th標簽。所有的html元素都科一被thymeleaf替換接管,格式為th:元素名
有無轉義
從controller傳一段信息
model.addAttribute("msg","<h1>王木木</h1>");
html中使用轉義和不轉義的情況
<div th:text="${msg}"></div>
<div th:utext="${msg}"></div>
運行結果
循環
同樣在controller里傳一段信息
model.addAttribute("users", Arrays.asList("wangmumu","王木木"));
接下來在html中進行取值
<h2 th:each="user:${users}" th:text="${user}"></h2>
運行結果
原文鏈接:https://blog.csdn.net/qq_43585922/article/details/125140423
相關推薦
- 2022-07-06 C++單例模式為何要實例化一個對象不全部使用static_C 語言
- 2022-05-29 Android?App如何防止抓包_Android
- 2022-12-04 深入了解Rust的切片使用_Rust語言
- 2022-02-09 C++解決輸出鏈表中倒數k個結點的問題_C 語言
- 2022-10-05 python?slack桌面自動化開發工具_python
- 2022-03-22 .NET?6開發TodoList開發查詢分頁_實用技巧
- 2022-04-24 Android為View添加拖放效果的方法實例_Android
- 2022-06-22 android使用intent傳遞參數實現乘法計算_Android
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支