thymeleaf模板引擎
1.引入依赖
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring5</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-java8time</artifactId>
</dependency>
2.controller
package com.kuang.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class IndexController {
@RequestMapping("/test")
public String index(Model model){
model.addAttribute("msg","hello");
return "test";
}
}
3.test.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<!--所有的html元素都可以被thymeleaf替换接管;th: 元素名-->
<div th:text="${msg}"></div>
</body>
</html>
4.测试访问
结论:
只要需要使用thymeleaf,只需要导入对应的依赖就可以了!我们将html放在我们的templates目录下即可!
thymeleaf的语法使用
-
导入约束
-
<html lang="en" xmlns:th="http://www.thymeleaf.org">
-
-
所有的html元素都可以被thymeleaf替换接管;th: 元素名
-
<div th:text="${msg}"></div>
-
thymeleaf语法
<body>
<!--所有的html元素都可以被thymeleaf替换接管;th: 元素名-->
<div th:text="${msg}"></div>
<div th:utext="${msg}"></div>
<!--
model.addAttribute("msg","<h1>嘻嘻哈哈</h1>");
上面正常,不识别h1标签,下面被转义了,识别了h1标签
-->
<!--遍历
model.addAttribute("users", Arrays.asList("张三","李四"));-->
<h3 th:each="user:${users}" th:text="${user}"></h3>
<!--<h3 th:each="user:${users}" >[[${user}]]</h3>-->
<!--这个也能取值,但不推荐-->
</body>
- 其他语法后续学习慢慢扩展
- @{}: 引进的链接 要替换成@{} 如src href