如何让所有thymeleaf页面获取后台的公用数据
时间: 2023-09-14 19:09:21 浏览: 52
要让所有Thymeleaf页面获取后台的公用数据,可以使用Thymeleaf的Context对象。
首先,在Controller中,将公用数据放入Context对象中,然后将Context对象添加到Model中:
```
@Controller
public class MyController {
@ModelAttribute
public void addCommonDataToModel(Model model) {
Context context = new Context();
context.setVariable("commonData", "公用数据");
model.addAttribute("context", context);
}
}
```
在Thymeleaf页面中,可以使用th:each和th:object来遍历Context对象中的所有属性:
```
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Thymeleaf Page</title>
</head>
<body>
<h1>Thymeleaf Page</h1>
<div th:each="entry : ${context.expressionObjects}">
<p>
<span th:text="${entry.key}"></span>: <span th:text="${entry.value}"></span>
</p>
</div>
</body>
</html>
```
这样,在所有Thymeleaf页面中,都可以使用${context.commonData}来获取公用数据了。
另外,如果需要在所有Thymeleaf页面中使用相同的布局或模板,可以使用Thymeleaf的布局功能。首先,定义一个布局模板:
```
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title th:text="${title}">Default Title</title>
</head>
<body>
<div th:replace="fragments/header :: header"></div>
<div th:replace="${content}"></div>
<div th:replace="fragments/footer :: footer"></div>
</body>
</html>
```
其中,fragments/header和fragments/footer是两个片段模板。在具体的页面中,可以使用Thymeleaf的片段替换功能来替换content属性:
```
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Thymeleaf Page</title>
</head>
<body>
<div th:replace="fragments/layout :: content">
<div th:replace="fragments/my-content :: myContent"></div>
</div>
</body>
</html>
```
这样,在所有Thymeleaf页面中,都可以使用相同的布局和模板了。