Thymeleaf 是一个跟 Velocity、FreeMarker 类似的模板引擎,它可以完全替代 JSP
pom.xml
添加依赖
<!-- thymeleaf -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!-- 允许使用非严格的 HTML 语法 -->
<dependency>
<groupId>net.sourceforge.nekohtml</groupId>
<artifactId>nekohtml</artifactId>
</dependency>
application.yml
自定义配置
spring:
# ThymeLeaf配置
thymeleaf: # ThymeleafProperties
prefix: classpath:/templates/ # thymeleaf模板文件前缀,可以自定义文件夹如classpath:/templates/temp
suffix: .html # thymeleaf模板文件后缀
mode: HTML5 # 视图模板类型
encoding: UTF-8 # 默认视图编码格式
cache: false # 配置页面缓存,thymeleaf默认开启缓存,页面不能及时刷新,需要关闭
servlet:
content-type: text/html # 响应类型
Controller
package com.example.web.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* @author dk
* @create 2022-06-27 3:06 PM
*/
@Controller
@RequestMapping("/web/test")
public class TestController {
@GetMapping("/index")
public String indexView(Model model) {
model.addAttribute("name", "haha");
return "index";
}
}
HTML
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<label th:text="'hello, ' + ${name}">
</body>
</html>
- 对
<html>
标签使用xmlns:th="http://www.thymeleaf.org"
声明使用 thymeleaf -
if
为true,则标签显示
<span th:if="${num > 10}">显示</span>
-
each
users是一个list,通过迭代器th:each对其进行遍历,每次迭代获取到的对象为user
<tr th:each="user : ${users}">
<td th:text="${user.nickname}">此处会被覆盖</td>
<td th:text="${user.username}"></td>
</tr>
switch
<td th:switch="${user.enabled}">
<span th:case="true">可用</span>
<span th:case="false">不可用</span>
</td>
-
<script th:src="@{lib/jquery.js}"></script>
引用static
的资源文件
网友评论