一、概述
1.是什么
模板引擎:(这里特指用于Web开发的模板引擎)是为了使用户界面与业务数据(内容)分离而产生的,它可以生成特定格式的文档,用于网站的模板引擎就会生成一个标准的HTML文档。
简单说, Thymeleaf 是一个跟 Velocity、FreeMarker 类似的模板引擎,它可以完全替代 JSP 。
2.特征
1.Thymeleaf 在有网络和无网络的环境下皆可运行,即它可以让美工在浏览器查看页面的静态效果,也可以让程序员在服务器查看带数据的动态页面效果。这是由于它支持 html 原型,然后在 html 标签里增加额外的属性来达到模板+数据的展示方式。浏览器解释 html 时会忽略未定义的标签属性,所以 thymeleaf 的模板可以静态地运行;当有数据返回到页面时,Thymeleaf 标签会动态地替换掉静态内容,使页面动态显示。
2.Thymeleaf 开箱即用的特性。它提供标准和spring标准两种方言,可以直接套用模板实现JSTL、 OGNL表达式效果,避免每天套模板、该jstl、改标签的困扰。同时开发人员也可以扩展和创建自定义的方言。
3. Thymeleaf 提供spring标准方言和一个与 SpringMVC 完美集成的可选模块,可以快速的实现表单绑定、属性编辑器、国际化等功能。
二、入门实例
1.引入依赖
springboot直接引入:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
非springboot项目使用如下依赖:
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf</artifactId>
<version>2.1.4</version>
</dependency>
thymeleaf配置的默认前缀为:“classpath:/templates/”,默认后缀为:".html",只要把html页面放在这个路径下,thymeleaf就可以帮我们自动渲染。
2.编写控制器
编写一个controller实现跳转到一个html页面,通过Model对象携带数据
在这@Controller
public class HelloController {
@RequestMapping("/success")
public String success(Model model){
//存入数据
model.addAttribute("msg","<h1>Hello</h1>");
model.addAttribute("users", Arrays.asList("小红", "小米","小白"));
//classpath:/templates/success.html
return "success";
}
}里插入代码片
3.编写模板html
success.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>success</h1>
<!--Thymeleaf语法:th:text就是将div中的内容设置为它指定的值-->
<div th:text="${msg}">你好</div>
<!--utext:会解析html,显示相应的效果-->
<div th:utext="${msg}">你好</div>
<!--each:遍历-->
<h3 th:each="user:${users}" th:text="${user}"></h3>
</body>
</html>在这里插入代码片
4.测试
通过http://localhost:8080/success路径访问到success.html页面,同时成功显示数据: