Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thymeleaf page layout header properties overriden

Ok so I'm using thymeleaf page layouts.

It seems to be working fine, however, I want to know how would I configure the <title></title> property in the <head></head> of a page that uses a fragment? Currently, everything in head is overriden by the header fragment (which can be seen below).

This is my: resources/templates/fragments/header.html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head th:fragment="header">
    <link href="../../static/css/bootstrap.min.css" th:href="@{css/bootstrap.min.css}" rel="stylesheet" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js" th:src="@{js/bootstrap.min.js}"></script>
</head>
<body></body>
</html>

This is my index page (I want the title tag to display):

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">

<head th:include="fragments/header :: header">
    <title>THIS DOES NOT SHOW</title>
</head>
<body>
    <div class="container">
        <div th:include="fragments/headerNavbar :: headerNavbar"></div>

        <h1>hey</h1>
        <div class="btn btn-success">button</div>
        <button class="btn btn-success">another</button>       
    </div>

This is the actual HTML output:

 <head>
    <link href="css/bootstrap.min.css" rel="stylesheet">
    <script src="js/bootstrap.min.js"></script>
</head>

I get what's going on. The header fragment is being loaded (included) into the head of my index page, thus its overriding all properties.

My problem is that I don't know how to have a header fragment AND have a file use that fragment while specifying a property, like a title.

This is what I have tried in index file:

<head>
    <div th:include="fragments/header :: header"></div>
    <title>THIS DOES NOT SHOW</title>
</head>

But it really messes up my HTML. There's got to a be a simple solution?

like image 228
benscabbia Avatar asked Oct 14 '25 11:10

benscabbia


1 Answers

Ok I found a way round it using this solution. I still think it's clunky, and I still think there must be a better way but for my needs this is sufficient (please do share a solution if you have one):

The magic is with the th:remove="tag", at runtime, the object tag is removed and displays the fragment appropriately:

<head>
    <title>THIS DOES SHOW</title>
    <object th:include="fragments/header :: header" th:remove="tag"><object> 
</head>

So now the output is:

<head>
    <title>THIS DOES SHOW</title>
    <link href="css/bootstrap.min.css" rel="stylesheet">
    <script src="js/bootstrap.min.js"></script>
</head>
like image 51
benscabbia Avatar answered Oct 17 '25 01:10

benscabbia



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!