thymeleaf 是 springboot 中流行使用的模板引擎,语法简单,功能强大。
thymeleaf 官方帮助文档(英文版)thymeleaf.pdf 提取密码: zev2
引入 thymeleaf
pom 文件引入 thymeleaf 依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
如果想要更改默认的版本,可加入如下代码更改 thymeleaf 版本
注意:thymeleaf-layout-dialect 的 2.0 及以上版本才开始支持 thymeleaf 的 3.0 以上版本
<properties>
<thymeleaf.version>3.0.11.RELEASE</thymeleaf.version>
<thymeleaf-layout-dialect.version>2.4.1</thymeleaf-layout-dialect.version>
</properties>
thymeleaf 的语法
引入名称空间
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
如果不引入名称空间,可以使用 data-th-属性 使用 thymeleaf 功能,如下
<p data-th-text="#{home.welcome}">Welcome to our grocery store!</p>
标准表达式语法
Simple expressions: 简单表达式
Variable Expressions: ${...} 变量表达式,获取变量的值,OGNL实现
1) 获取对象的属性、调用方法
例如:
${person.father.name}
${personsByName['Stephen Zucchini'].age}
${person.createCompleteName()}
2) 使用内置的基本对象
#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.
#s