3.5使用thymeleaf渲染Web页面
3.5.1什么是thymeleaf
thymeleaf是一款用于渲染XML/XHTML/HTML5内容的模板引擎,类似JSP,Velocity,FreeMaker等,它也可以轻易的与Spring MVC等Web框架进行集成作为Web应用的模板引擎。
3.5.2 Maven依赖
<!--Spring SpringMVC --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!--引入thymeleaf的依赖--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
3.5.3 配置文件新增
###ThymeLeaf配置 spring: thymeleaf: #prefix:指定模板所在的目录 prefix: classpath:/templates/ #check-tempate-location: 检查模板路径是否存在 check-template-location: true #cache: 是否缓存,开发模式下设置为false,避免改了模板还要重启服务器,线上设置为true,可以提高性能。 cache: true suffix: .html encoding: UTF-8 mode: HTML5
3.5.4 案例代码
<!DOCTYPE html> <!--需要在HTML文件中加入以下语句: --> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Show User</title> </head> <body> <table> 姓名:<span th:text="${user.userName}"></span> 年龄:<span th:text="${user.age}"></span> </table> </body> </html>
3.5.4 高级写法
循环语句:
<ul th:each="user:${userList}"> <li th:text="${user.userName}"></li> <li th:text="${user.age}"></li> <br> </ul>
If判断:
<span th:if="${user.age>17}">已经成年啦</span> <span th:if="${user.age<17}">未成年</span>
详细可以更多语法可以查看https://www.thymeleaf.org/documentation.html
1.B站在线学习地址:
2. 百度云盘视频和文档下载:
链接:
提取码:1234
链接: