Head and Title in Thymeleaf

Andrea Colleoni picture Andrea Colleoni · Jul 16, 2015 · Viewed 30.2k times · Source

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?

Answer

tarish picture tarish · Jul 24, 2015

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:

  1. The differences between th:include and th:replace
  2. Referencing fragments by domselector instead of by th:fragment
  3. 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>

Hope this helps!