Thymeleaf模板引擎
一、Thymeleaf是什么?
简单说, Thymeleaf 是一个跟 Velocity、FreeMarker 类似的模板引擎,它可以完全替 代 JSP.
文档
推荐官方文档
二、使用步骤
springboot引入依赖:
<dependency>
<groupId>nz.net.ultraq.thymeleaf</groupId>
<artifactId>thymeleaf-layout-dialect</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.1.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.10</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
application.properties
spring.thymeleaf.cache=false
关闭thymeleaf的缓存
1.表达式
在html文件中的html标签中添加 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>
欢迎您,<span th:text="${user.userName}">1111</span>
</body>
</html>
th:text="${user.userName}" 输出数据
输出数据:<span th:text="${userName}">userName</span>
拼接数据:<span th:text="|Hello ${userName}|">userName</span>
获取request<p th:text="${#request.getAttribute('test')}"></p>
两个不同作用域的,输出:req<p th:text="${test}"></p>
获取session<p th:text="${session.test}"></p>
格式化日期<p th:text="${#dates.format(date,'yyyy-MM-dd HH:mm:ss')}"></p>
<p th:text="${#dates.createToday()}">2020-11-11</p>
2.页面布局
footer 页面
<footer th:fragment="copyright">
@2020 aiwieiyi
</footer>
index页面引用footer 页面
<div th:insert="demo/layout/footer :: copyright"></div>
<div th:replace="demo/layout/footer :: copyright"></div>
结果
引用js,css
th:href="@{/css/bootstrap.min.css}" 方式
<link th:href="@{/css/bootstrap.min.css}" href="../static/css/bootstrap.min.css" rel="stylesheet">
<!-- Font Awesome -->
<link th:href="@{/css/font-awesome.min.css}" rel="stylesheet">
<!-- NProgress -->
<link th:href="@{/css/nprogress.css}" rel="stylesheet">
<!-- Animate.css -->
<!-- Custom Theme Style -->
<link th:href="@{/css/custom.min.css}" rel="stylesheet">