Thymeleaf简介:
开发传统Java WEB工程时,我们可以使用JSP页面模板语言,但是在SpringBoot中已经不推荐使用了。SpringBoot支持如下页面模板语言
- Thymeleaf
- FreeMarker
- Velocity
- Groovy
- JSP
当你使用上述模板引擎中的任何一个,它们默认的模板配置路径为:src/main/resources/templates。当然也可以修改这个路径,具体如何修改,可在后续各模板引擎的配置属性中查询并修改。
Thymeleaf Thymeleaf是一个XML/XHTML/HTML5模板引擎,可用于Web与非Web环境中的应用开发。它是一个开源的Java库,基于Apache License 2.0许可,由Daniel Fernández创建,该作者还是Java加密库Jasypt的作者。 Thymeleaf提供了一个用于整合Spring MVC的可选模块,在应用开发中,你可以使用Thymeleaf来完全代替JSP或其他模板引擎,如Velocity、FreeMarker等。Thymeleaf的主要目标在于提供一种可被浏览器正确显示的、格式良好的模板创建方式,因此也可以用作静态建模。你可以使用它创建经过验证的XML与HTML模板。相对于编写逻辑或代码,开发者只需将标签属性添加到模板中即可。接下来,这些标签属性就会在DOM(文档对象模型)上执行预先制定好的逻辑。
上面并没有列举所有SpringBoot支持的页面模板技术。其中Thymeleaf是SpringBoot官方所推荐使用的,下面来谈谈Thymeleaf一些常用的语法规则
默认在.html模板的基础写法示例:
<!DOCTYPE>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Hello Thymeleaf</title>
</head>
<body>
<div>
<span>访问 Model:</span><span th:text="${key}"></span>
</div>
</body>
</html>
注意:
1、记得每个文件都要添加 xmlns:th="http://www.thymeleaf.org" 声明才能使用thymeleaf语法
2、Thymeleaf的.html模板默认在:“src/main/resources/templates” 路径下的templates文件夹里,templates文件夹没有则需要新增【且.html模板也可以通过配置更改到“WEB_INF”下】
引入maven
springboot引入:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
非springboot引入:
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf</artifactId>
<version>2.1.4</version>
</dependency>
实操:
@RequestMapping("thymeleaf")
public String thymeleaf(Model model) {
model.addAttribute("key",111);
return "home";
//直接返回.html模板的名字即可,如果有文件夹则在前面加上文件夹名称
}
//home.html 的测试示例:
<!DOCTYPE>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Hello Thymeleaf</title>
</head>
<body>
<div>
<span>访问 Model:</span><span th:text="${key}"></span>
</div>
</body>
</html>
th标签基础用法:
th:text 【给当前标签替换文本,包括html,正确写法:p th:text="#{home.welcome}">p>】
th:id 【替换ID,正确写法:】
th:value 【属性赋值,正确写法:】
th:style 【设置css样式,正确写法:】
th:onclick 【设置点击事件,正确写法:
传参写法:th:οnclick="'javascript:consultClick(\''+${user.phone}+'\');'"】
th:if 【条件判断,正确写法:空list判断:th:if="${#lists.isEmpty(dataResultList)}"】