Thymeleaf layout dialect and th:replace in head causes title to be blank

可紊 提交于 2019-12-01 04:44:23
iaforek

Finally, I've found a way to achieve what I wanted.

In layout file <title> tag must stay. All other tags I grouped with <object> tag and annotated it as follows:

<head>
  <title layout:title-pattern="$CONTENT_TITLE">Layout Title will be replaced by Page Title!</title>
  <object th:include="/html/components/head :: head" th:remove="tag" />
</head>

In my html/components/head.htm file I had to remove <title> tag so it won't be duplicated after include.

<head th:fragment="head">
  <meta charset="utf-8" />
  <!-- NO TITLE TAG HERE -->
  ...
</head>

This way head fragment is included in <object> tag and thanks to th:remove="tag" <object> tag gets removed and my final HTML output is:

<head>
  <title>My content title</title>
  <meta charset="utf-8" />
  <!--  NO TITLE TAG HERE -->
  ...
</head>

Obviously, I removed NO TITLE TAG HERE message too, once I got it working.

I think I found a slightly less verbose way to for using th:replace and th:fragment together, e.g. to include common <head> metadata and static resource includes in your pages.

Put the th:remove="tag" in the fragment definition, so you don't have to repeat the th:remove="tag" everytime including it.

fragment_head.html

<thymeleaf xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" 
    th:fragment="head" th:remove="tag">

    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <link rel="stylesheet" th:href="@{/css/vendor/bootstrap.min.css}"/>

</thymeleaf>

mypage.html

<head>
    <thymeleaf th:replace="fragment_head :: head" />
</head>

You can replace whole head tag.

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head lang="pl" th:replace="fragments/head :: head">
</head>
<body>
 ...
</body>
</html>

resources/templates/fragments/head.html:

    <head lang="pl">
        <title>Title</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
        <link href="http://cdn.jsdelivr.net/webjars/bootstrap/3.3.5/css/bootstrap.min.css"
              th:href="@{/webjars/bootstrap/3.3.5/css/bootstrap.min.css}"
              rel="stylesheet" media="screen" />

        <script src="http://cdn.jsdelivr.net/webjars/jquery/2.1.4/jquery.min.js"
                th:src="@{/webjars/jquery/2.1.4/jquery.min.js}"></script>
        <link href="../static/css/mycss.css"
              th:href="@{css/mycss.css}" rel="stylesheet" media="screen"/>
    </head>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!