我的结构
WEB-INF
└── thymeleaf
├── fragments
│ └── head.html
├── index
│ └── index.html
└── layout.html
layout.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head th:insert="~{fragments/head :: head}" th:remove="tag"></head>
<body>
<!--${view} == "index/index"-->
<div th:insert="~{${view} :: content}" th:remove="tag"></div>
</body>
</html>
index.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title id="pageTitle">My Title with ID</title>
</head>
<body>
<div th:fragment="title">My Title With fragment</div>
<div th:fragment="content">
My page
</div>
</body>
</html>
head.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head th:fragment="head" th:remove="tag">
<meta charset="utf-8">
<title>??????</title>
<link href="/css/bootstrap.css" rel="stylesheet">
</head>
<body>
</body>
</html>
我是Spring
和thymeleaf
的新人。我试图构建一个简单的crud
,但我遇到了以下情况:
我想要的是:在index.html
设置title
变量并在head.html
fragment
中检索此title
变量并打印出来。
我该怎么办?
答案 0 :(得分:3)
我认为你正在寻找8.3 Flexible layouts该文档很棒且易于理解,但这里也只是插入标题字符串的简单案例
<强>布局/的layout.html 强>
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" th:fragment="page(title)">
<head th:replace="fragments/head :: common_header(title=${title})"></head>
<body>
<div th:replace="this :: content"></div>
</body>
</html>
<强>片段/ head.html 强>
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head th:fragment="common_header(title)">
<title th:text="${title}">The awesome application</title>
</head>
<body></body>
</html>
index.html (indexTitle
来自控制器,或者您可以将字符串放在那里)
<html xmlns:th="http://www.thymeleaf.org"
th:include="layouts/layout :: page(title=${indexTitle})">
<head></head>
<body>
<section th:fragment="content">
<div class="block">Part of index.html</div>
</section>
</body>
</html>
此处还可以使用
中的一个项目简化github demo答案 1 :(得分:0)
你应该使用th:include。
的index.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head th:include="header :: title">
</head>
<body>
<div>My Title With fragment</div>
<div>
My page
</div>
</body>
</html>
head.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head th:fragment="title" >
<title>??????</title>
</head>
<body>
</body>
</html>