I'm a Thymeleaf beginner.
I started with a common layout page:
fragments/layout.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head th:fragment="headerFragment">
<title>Template title</title>
<!-- metas, link and scripts -->
</head>
<body>
<div class="container">
Some text
</div>
</body>
</html>
And a content page:
page.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head th:include="fragments/layout :: headerFragment">
<title>Page title</title>
<!-- metas, link and scripts -->
</head>
<body>
<div class="container">
Some text
</div>
</body>
</html>
When I render the page, the title is always from the template, not from the page.
Is it possible in Thymeleaf to have metas, scripts and style in common (in the HEAD tag) but to have a per-page title?
解决方案
I was also having this problem (Thank you nmy for referencing the documentation!) Here is what I noticed and how I solved it in my app:
Things to note from the documentation:
The differences between th:include and th:replace
Referencing fragments by domselector instead of by th:fragment
Thymeleaf provides a "this" option for finding selectors
With these 3 things in mind, you can do the following:
fragments/layout.html:
<head th:fragment="headerFragment">
<title th:include=":: #pageTitle">Layout Generic Title< /title>
<!-- metas, link and scripts -->
</head>
page.html
<head th:include="fragments/layout :: headerFragment">
<title id="pageTitle">Page title</title>
<!-- other elements you want to reference in your layout -->
</head>