一、thymeleaf
1.1 模板引擎功能
将外部的数据填充到对应页面的动态部分,最终生成我们需要的页面。
1.2 引入thymeleaf
添加依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
如果需要使用到3以上版本:加进去要去掉:properties标签
<properties>
<thymeleaf.version>3.0.2.RELEASE</thymeleaf.version>
<!--thymeleaf3版本 适配布局功能2及其以上版本-->
<thymeleaf-layout-dialect.version>2.1.1</thymeleaf-layout-dialect.version>
</properties>
1.3 thymeleaf自定配置类的路径
1.4 thymeleaf默认规则
二、 thymeleaf语法
2.1 引入thymeleaf名称空间
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
2.2 thymeleaf优点
- 使前后端更好的分离
如果页面不经过thymeleaf解析,直接显示的是前段的信息,经过thymeleaf解析之后,也会显示后端的数据
2.3 语法规则
- th:text
修改文本内容,转义 - th:utext
修改文本内容,不转义特殊字符 - th:id=${id}
修改标签的id - th:each
遍历 - th:if
判断 - th:href
- th:value
2.4 使用的内置对象
#ctx : the context object.
#vars: the context variables.
#locale : the context locale.
#request : (only in Web Contexts) the HttpServletRequest object.
#response : (only in Web Contexts) the HttpServletResponse object.
#session : (only in Web Contexts) the HttpSession object.
#servletContext : (only in Web Contexts) the ServletContext object.
举例:
Established locale country: <span th:text="${#locale.country}">US</span>.
对应pdf:
2.5 使用的内置工具类
举例:
${#numbers.sequence(from,to)
${#numbers.sequence(from,to,step)
对应pdf:
2.6 *{…}表达式
配合th:object使用,下面两段同样的效果
<div th:object="${session.user}">
<p>Name: <span th:text="*{firstName}">Sebastian</span>.</p>
<p>Surname: <span th:text="*{lastName}">Pepper</span>.</p>
<p>Nationality: <span th:text="*{nationality}">Saturn</span>.</p>
</div>
<div>
<p>Name: <span th:text="${session.user.firstName}">Sebastian</span>.</p>
<p>Surname: <span th:text="${session.user.lastName}">Pepper</span>.</p>
<p>Nationality: <span th:text="${session.user.nationality}">Saturn</span>.</p>
</div>
对应pdf中:
2.7 #{…}表达式
取国际化内容
<p th:utext="#{home.welcome}">Welcome to our grocery store!</p>
对应pdf中:
2.8 @{…}表达式
以前链接后面的参数需要拼串,现在不需要
<!-- Will produce 'http://localhost:8080/gtvg/order/details?orderId=3' (plus rewriting) -->
<a href="details.html"
th:href="@{http://localhost:8080/gtvg/order/details(orderId=${o.id})}">view</a>
对应pdf中:
2.9 测试th:each,th:text
//测试thymeleaf模板的遍历
@RequestMapping(value = "/hello",method = RequestMethod.GET)
public String say_foreach(Map<String,Object> map){
map.put("hello", "你好");
map.put("users", Arrays.asList("张三","李四","王五"));
return "a";
}
结果:
三、入门的例子
3.1 Hello.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>你好呀,恭喜你学会了thymeleaf木板</h1>
<div th:text="${Hello}">这是欢迎信息</div>
</body>
</html>
3.2 Controller
@Controller
public class test {
@RequestMapping("/thymeleaf")
public String hello(Model model){
model.addAttribute("Hello","这是一个字符串");
return "Hello";
}
}