I am using the latest version of thymeleaf page layouts.
I want to use the title pattern $CONTENT_TITLE - $LAYOUT_TITLE
for all my pages. Therefore, I created the following layout and content files.
My layout.html
file looks like
<!doctype html>
<html xmlns:th="http://www.thymeleaf.org" xmlns:layout="http://www.w3.org/1999/xhtml">
<head>
<title layout:title-pattern="$CONTENT_TITLE - $LAYOUT_TITLE">My Company Name</title>
<!-- some scripts and styles --->
</head>
<body>
<!-- some content --->
</body>
</html>
My content.html
looks like
<!DOCTYPE html>
<html xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" xmlns:th="http://www.thymeleaf.org"
layout:decorate="~{layout.html}">
<head>
<title>
<th:block th:if="${meta.pageTitle}" th:text="${meta.pageTitle}"></th:block>
</title>
</head>
<body>
<!-- some content --->
</body>
</html>
If the content page gets Newsletter
as value for the property pageTitle
and I call the content page in my browser, I get the correct result:
<title>Newsletter - My Company Name</title>
If my content page does not have a title, I only want to display the $LAYOUT_TITLE
in my <title>
tag without the leading separator -
. Howerver, with my code I get
<title>- My Company Name</title>
What I want is
<title>My Company Name</title>
How can I achieve that in a simple way? As far as I know, I cant use the $CONTENT_TITLE
in the layout.html and check if it is empty, or can I?
Since i could not find a way to use conditions for the title-pattern I moved away from this and used parameterizable fragments as suggested in this answer.
layout.html
<!doctype html>
<html xmlns:th="http://www.thymeleaf.org" xmlns:layout="http://www.w3.org/1999/xhtml">
<head>
<!-- some scripts and styles --->
</head>
<body>
<!-- some content --->
</body>
</html>
content.html
<!doctype html>
<html xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" xmlns:th="http://www.thymeleaf.org"
layout:decorate="~{layout.html}">
<head>
<th:block th:replace="./fragments/page-title.html :: page-title('My Content Title')"></th:block>
</head>
<body>
<!-- some content --->
</body>
</html>
./fragments/page-title.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head th:fragment="page-title(pageTitle)" th:remove="tag">
<title th:text="(${pageTitle}? ${pageTitle} + ' - ' : '') + 'My Company Name'"></title>
</head>
</html>
This results in
<title>My Content Title - My Company Name</title>
for all pages with an additional title and <title>My Company Name</title>
for all pages without an additional title (like my start page).