Thymeleaf模板引擎
结论:只要需要使用thymeleaf,只需要导入对应的依赖就可以了!我們將html放在我们的templates目录下即可。
public static final String DEFAULT_PREFIX = "classpath:/templates/";
public static final String DEFAULT_SUFFIX = ".html";
所用依赖:
<!--Thymeleaf,我们都是基于3.x-->
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring5</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-java8time</artifactId>
</dependency>
如何使用?
- 是变量直接使用:${…}
- 如果是一些选择的表达式使用:*{…}
- 如果是信息使用:#{…}
- 如果是url使用:@{…}
- 如果是片段表达式使用:~{…}
后端传值到前端:
后台的controller
//在templates目录下的所有页面,只能通过controller来跳转
//这个需要模板引擎的支持thymeleaf
@Controller
public class IndexController {
@RequestMapping("/a")
public String index(Model model){
model.addAttribute("msg","hello,springboot");
model.addAttribute("users", Arrays.asList("ws","xs"));
return "index";
}
}
前端index.html
<!DOCTYPE html>
<!--使用thymeleaf一定要导入约束条件xmlns:th="http://www.thymeleaf.org"-->
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<!--获取单个值-->
<div th:text="${msg}"></div>
<!--th:text不转译,th:utext转译-->
<div th:utext="${msg}"></div>
<!--遍历数组-->
<div th:each="user:${users}" th:text="${user}"></div>
</body>
</html>
后台模板:x-admin