官网:https://www.thymeleaf.org/ 使用步骤:
导入pom <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> 创建test.html测试(再/resource/temple下创建)需要导入<html lang="en" xmlns:th="http://www.thymeleaf.org"> <!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div th:text="${msg}"></div> </body> </html> Controller类测试: @Controller public class TestController { @RequestMapping("/test") public String test(Model model){ model.addAttribute("msg","This is a test"); return "test"; } } 效果:可以参考官方使用文档:https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.pdf 可以看到一些使用规则:我们可以用th:attr来替换HTML中原生属性值
传递一个内容里面有标签的数据:th:text不会管,th:utext则会转义这个标签
@RequestMapping("/test") public String test(Model model){ model.addAttribute("msg","<h1>This is a test</h1>"); return "test"; }Fragment iteration th:each官方文档写道用th:each
传递一个集合:
@RequestMapping("/test") public String test(Model model){ model.addAttribute("msg","<h1>This is a test</h1>"); //Arrays.asList()把一个数组转化为一个集合 model.addAttribute("students", Arrays.asList("小明","向辉","小红","李华")); return "test"; }test.html:
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org" xmlns:tiles="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div th:utext="${msg}"></div> <h2 th:each="student:${students}" th:text="${student}"></h2> <!--或<h2 th:each="student:${students}" >[[ ${student} ]]</h2> --> </body> </html>