Insert template without overriding childs in Thymeleaf (default head template)

I am used to th:insert and th:replace but I need a way to include a fragment in a header without overriding other tags inside head.

I tried this, but the home.css head gets completely overwritten:

home.html:

<head th:include="fragments/head :: genericHead">
    <link rel="stylesheet" href="home.css">
</head>

Head template:

<head th:fragment="genericHead">
    <link rel="stylesheet" href="common.css">
</head>

I want some way to do a th:add or similar in order to have both links as childs of head and which results in something like this:

<head>
    <link rel="stylesheet" href="common.css">
    <link rel="stylesheet" href="home.css">
</head>

Upvotes: 1

Views: 543

Answers (1)

You can use the th:block together with th:include / th:replace

Your home.html would look like:

<head>
    <th:block th:include="fragments/head :: genericHead"></th:block>
    <link rel="stylesheet" href="../static/home.css">
</head>

And the fragment would look exactly the same:

<head th:fragment="genericHead">
    <link rel="stylesheet" href="common.css">
</head >

The th:block will execute the include and then it will desappear (so it can be a include or also a replace, it doesn't matter after all) leaving us with the content of the fragment tag.

Upvotes: 1

Related Questions