thymeleaf的使用和语法
thymeleaf的使用
thymeleaf是一种模板引擎,使用它只需要添加依赖即可。下面是三种可以找到的地址:
Thymeleaf 官网:https://www.thymeleaf.org/
Thymeleaf 在Github 的主页:https://github.com/thymeleaf/thymeleaf
Spring官方文档:找到我们对应的版本
https://docs.spring.io/spring-boot/docs/2.2.5.RELEASE/reference/htmlsingle/#using-boot-starter
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
需要展示的前端页面放到templates文件夹下。
语法
要使用thymeleaf语法,需要在html文件中导入命名空间的约束,方便提示。
xmlns:th="http://www.thymeleaf.org"
测试1
编写前端页面:
<!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
public class TestController {
@RequestMapping("/test")
public String test(Model model){
model.addAttribute("msg","hello,thymeleaf");
return "test";
}
}
可以测出结果为hello,thymeleaf。
测试2
<!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>
<!--不转义-->
<div th:utext="${msg}"></div>
<h1 th:each="user:${users}" th:text="${user}"></h1>
<!--行内写法:官网#12-->
<h1 th:each="user:${users}">[[${user}]]</h1>
</body>
</html>
@Controller
public class Test2Controller {
@RequestMapping("/t1")
public String test1(Map<String,Object> map){
map.put("msg","<h1>hello</h1>");
map.put("users", Arrays.asList("chenhang","hangchen"));
return "test1";
}
}
浙公网安备 33010602011771号