Issue
please, I want ask something about parametrized fragments in Thymeleaf. I have homepage.html , it is thymeleaf template to which I am sending Model model by Controller (Java, Spring). this model has this value: "AllComments: listOfComments". listOfComments is varirable of type List with Comment objects in.
I want to use this "AllComments" variable in fragment "comment". (to print table). How can I send this variable from homepage.html through layout.html to fragment in fragments.html ? Thank you for answer.
<!--
folder : ..../templates
homepage.html
to this template i am sending Model model with: "AllComments: listOfComments".
listOfComments is varirable of type List<Comments> with Comment objects in.
-->
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{layout/layoutPage.html}"
lang="sk">
<head>
<title>My Page</title>
</head>
<body>
<main layout:fragment="content">
</main>
</body>
</html>
<!--
folder: ..../layout
layoutPage.html -->
<!DOCTYPE html>
<html lang="sk"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<main layout:fragment="content"></main>
<div th:replace="fragments/fragments :: comments" />
<footer th:replace="fragments/fragments :: footer" />
</body>
</html>
<!--
folder: ..../fragments
fragments.html -->
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" lang="sk">
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<!--fragment footer-->
<footer th:fragment="footer">
<hr>
<p>Footer: xxx</p>
<hr>
</footer>
<!--fragment comment-->
<div th:fragment="comments(AllComments)">
<table class="comments">
<thead>
<tr>
<th> Username </th>
<th> Comment </th>
<th> Commented On</th>
</tr>
</thead>
<tbody>
<tr th:if="${AllComments.empty}">
<td colspan="2"> No Comments Available </td>
</tr>
<tr th:each="item : ${AllComments}">
<td><span th:text="${item.username}"> </span></td>
<td><span th:text="${item.comment}"> </span></td>
<td><span th:text="${item.commentedOn}"> </span></td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
Solution
Just pass the variable to where you use the fragment:
<div th:replace="fragments/fragments :: comments(${AllComments})" />
Answered By - Wim Deblauwe
Answer Checked By - Cary Denson (JavaFixing Admin)