日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

如何在springboot中使用Thymeleaf

作者:奔走的王木木Sir 更新時間: 2022-06-08 編程語言

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

欄目分類
最近更新