1.介绍
Thymeleaf是Spring boot推荐使用的模版引擎
2.SpringBoot中引入
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
3.配置
1.默认配置
- 默认前缀 classpath:/templates/
- 默认后缀 .html
更多如下:
@ConfigurationProperties(
prefix = "spring.thymeleaf"
)
public class ThymeleafProperties {
private static final Charset DEFAULT_ENCODING;
public static final String DEFAULT_PREFIX = "classpath:/templates/";
public static final String DEFAULT_SUFFIX = ".html";
private boolean checkTemplate = true;
private boolean checkTemplateLocation = true;
private String prefix = "classpath:/templates/";
private String suffix = ".html";
private String mode = "HTML";
private Charset encoding;
private boolean cache;
private Integer templateResolverOrder;
private String[] viewNames;
private String[] excludedViewNames;
private boolean enableSpringElCompiler;
private boolean renderHiddenMarkersBeforeCheckboxes;
private boolean enabled;
private final Servlet servlet;
private final Reactive reactive;
public ThymeleafProperties() {
this.encoding = DEFAULT_ENCODING;
this.cache = true;
this.renderHiddenMarkersBeforeCheckboxes = false;
this.enabled = true;
this.servlet = new Servlet();
this.reactive = new Reactive();
}
2.修改配置
在application.properties文件中已spring.thymeleaf前缀进行修改
# ThymeleafProperties
spring.thymeleaf.cache=false
spring.thymeleaf.encoding=UTF-8
4.使用
1.在页面中加入命名空间
<html lang="en" xmlns:th="http://www.thymeleaf.org">
2.按照语法修改html页面
1.标准表达式
- ${...} 变量表达式
- @{...} 链接URL表达式
- *{...} 选择变量表达式
- #{...} 消息表达式
- ~{...} 片段表达式
2.替换页面内容
1.替换文字
- th:text 替换文本
- th:utext 支持html的文本替换。
<div th:text="${usernameMsg}">
该账号不存在!
</div>