Bruno Rozendo
Bruno Rozendo

Reputation: 337

Pass variable between fragments Thymeleaf

My structure

WEB-INF
└── thymeleaf
    ├── fragments
    │   └── head.html
    ├── index
    │   └── index.html
    └── layout.html

layout.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head th:insert="~{fragments/head :: head}" th:remove="tag"></head>
<body>
    <!--${view} == "index/index"-->
    <div th:insert="~{${view} :: content}" th:remove="tag"></div>
</body>
</html>

index.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title id="pageTitle">My Title with ID</title>
</head>
<body>
<div th:fragment="title">My Title With fragment</div>
<div th:fragment="content">
    My page
</div>
</body>
</html>

head.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head th:fragment="head" th:remove="tag">
    <meta charset="utf-8">
    <title>??????</title>
    <link href="/css/bootstrap.css" rel="stylesheet">
</head>
<body>
</body>
</html>

I'm new to Spring and Thymeleaf. I'm trying to build a simple CRUD, but I'm stuck in the following situation:

What I want is: in index.html set a title variable and in head.html fragment retrieve this title variable and print it.

What can I do?

Upvotes: 3

Views: 10800

Answers (2)

varren
varren

Reputation: 14731

I think you are looking for 8.3 Flexible layouts The documentation is awesome and easy to follow, but here is also simple case for just inserting title string

layouts/layout.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" th:fragment="page(title)">
    <head th:replace="fragments/head :: common_header(title=${title})"></head>
    <body>
        <div th:replace="this :: content"></div>
    </body>
</html>

fragments/head.html

<!DOCTYPE html>
<html  xmlns:th="http://www.thymeleaf.org">
    <head th:fragment="common_header(title)">
        <title th:text="${title}">The awesome application</title>
    </head>
    <body></body>
</html>

index.html (indexTitle comes from controller or you can just put string there)

<html xmlns:th="http://www.thymeleaf.org"
      th:include="layouts/layout :: page(title=${indexTitle})">
    <head></head>
    <body>
        <section th:fragment="content">
           <div class="block">Part of index.html</div>
        </section>
    </body>
</html>

And here is also simplified github demo from one of my project you can play with

Upvotes: 15

Ketan Bhavsar
Ketan Bhavsar

Reputation: 5396

You should use th:include.

index.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head th:include="header :: title">
</head>
<body>
<div>My Title With fragment</div>
<div>
    My page
</div>
</body>
</html>

head.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head th:fragment="title" >
    <title>??????</title>
</head>
<body>
</body>
</html>

Upvotes: 0

Related Questions