- `Thymeleaf`模板引擎
- 1.入门
- 2.使用`spring.thymeleaf`可以修改掉模板引擎中的默认配置
- 表达式
- 1.标准变量表达式
- 2.选择变量表达式
- 3.链接表达式`URL`
- `Thymeleaf`属性
- 1.`th:action`
- 2.`th:method`
- 3.`th:href`
- 4.`th:src`
- 5.`th:text`
- 6.`th:style`
- 7.`th:each`[重点]
- A.`List`集合
- B.数组
- C.`Map`集合
- 8.条件判断`if`-`unless`
- 9.`th:switch`
- 10.`th:inline`
- 内联`text`
- 内联`javascript`
- 11.字面量
- 12.字符串连接
- 13.运算符
- `Thymeleaf`基本对象
- 1.常用内置对象
- 2.基于内置对象`#ctx`
- 3.内置工具类
- 4.模板内容复用
- ` th:insert` `th:replace` `th:include`三者的区别
第一步:创建一个SpringBoot工程
引入相关的场景启动器
org.springframework.boot spring-boot-starter-thymeleaf org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-devtools runtime true org.projectlombok lombok true org.springframework.boot spring-boot-starter-test test org.springframework.boot spring-boot-maven-plugin org.projectlombok lombok
第二步:编写控制器层
@Controller
public class ThymeleafController {
@RequestMapping("/")
public String helloThymeleaf(Model model){
// 向request域中存储数据
model.addAttribute("data","欢迎使用Thymeleaf模板引擎");
return "hello";
}
}
第三步:编写页面,向request共享域中获取出数据
hello页面
Thymeleaf模板引擎的使用
数据显示区域
#修改端口号为 80 server.port=80 #在开发阶段,一般会关闭模板缓存 ,让修改立即生效,默认是true开启的, #在项目上线后,要修改回开启 spring.thymeleaf.cache=false #编码模式 spring.thymeleaf.encoding=UTF-8 #模板的类型(默认是html,模板是html文件) spring.thymeleaf.mode=HTML #模板的前缀:类路径的: classpath:/templates/ spring.thymeleaf.prefix=classpath:/templates/ #模板的后缀: spring.thymeleaf.suffix=.html表达式 1.标准变量表达式
语法:
${key}
作用:获取key对于的文本数据,key是request作用域中的key,使用request.setAttribute();或model.addAttribute();
在页面中的html标签中,使用th:text="${key}"
案例:
第0步:编写JavaBean
@Data
@NoArgsConstructor
@AllArgsConstructor
@ToString
public class Person {
private Integer id;
private String name;
private String sex;
private Integer age;
}
第一步:编写控制器
@RequestMapping("/expressionl")
public String expressionl(Model model){
// 向request共享域中存储数据
model.addAttribute("site","https://fanyi.baidu.com/");
model.addAttribute("pojo",new Person(101,"海康","男",23));
// 指定跳转视图
return "standard";
}
第二步:编写页面
第三步:测试
2.选择变量表达式语法:
*{key}
说明:需要配和th:object一起使用,选择变量表达式,也叫星号变量表达式,使用th:object属性来绑定对象,选择表达式首先使用th:object来绑定后台传来的对象,然后使用*来代表这个对象后面{}中的值此对象的属性
选择变量表达式*{...}是另一种类似于标准变量表达式${...}表示变量的方法,选择变量表达式*{...}在执行时是在选择的对象上求解,而${...}是在上下文的变量model上求解
选择变量表达式使用步骤:
第一步:"
第二步:th:text="*{对象属性}"
案例:
第0步:
@Data
@NoArgsConstructor
@AllArgsConstructor
@ToString
public class Person {
private Integer id;
private String name;
private String sex;
private Integer age;
}
第一步:编写控制器
@RequestMapping("/expression2")
public String expression2(Model model){
model.addAttribute("pojo",new Person(102,"湛江","男",23));
return "expression2";
}
第二步:编写页面
选择器表达式
id
name
sex
age
第三步:测试
3.链接表达式URL
语法:
@{链接url}
说明:主要用来链接,地址的展示,可用于



