模板引擎thymeleaf
当项目以jar包的方式进行打包,并且该boot项目中有嵌入式的tomcat的时候,该项目就不支持类似于jsp的动态页面,如果只用静态的html页面的话,开发会极不方便,这时我们就需要引入一个模板引擎。
spring boot 推荐使用thymeleaf 模板引擎!
thymeleaf在spring boot项目中的引用
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
版本系统会自动配置好,当然也可以自行设置 thymeleaf 的版本,切换thymeleaf版本:
<properties>
<thymeleaf.verson>3.0.9</thymeleaf.verson>
<!-- 布局功能的支持程序 thymeleaf3主程序 layout2以上版本 -->
<!-- thymeleaf2 layout1版本 -->
<thymeleaf-layout-dialect.version>2.2.2</thymeleaf-layout-dialect.version>
</properties>
thymeleaf的语法格式
在IDEA中按住ctrl+N可以搜索类名,按此方式找到ThymeleafProperties类,在该类中可以看到:
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";
在thymeleaf包 中已经帮我们自动引入了返回字符串的前缀和后缀渲染。
只要我们把HTML页面放在classpath:/templates/中,thymeleaf就能帮我们自动渲染。
使用:
- 导入命名空间
在相应的html页面上端,导入thymeleaf的命名空间
<html lang="en" xmlns:th="http://www.thymeleaf.org">
- 使用thymeleaf的语法
th:text;改变当前元素里面的文本内容;
th:任意html;来替换原生属性的值
等等,更详细的参照官方文档(中文版)
链接:https://pan.baidu.com/s/1lGHYR1MW8qrGnCoQmBarQw
提取码:qth6