Thymeleaf – parametrized fragment – how send data from template, to layout and then to fragment?


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 
to this template i am sending Model model with: "AllComments: listOfComments".
listOfComments is varirable of type List<Comments> with Comment objects in.
<html xmlns:th=""
 <title>My Page</title>


<main layout:fragment="content">


 folder: ..../layout
 layoutPage.html  -->
 <!DOCTYPE html>
 <html lang="sk"
     <meta charset="UTF-8" />
     <meta name="viewport" content="width=device-width, initial-scale=1">
 <main layout:fragment="content"></main>
 <div th:replace="fragments/fragments :: comments" />
 <footer th:replace="fragments/fragments :: footer" />

     folder: ..../fragments
     fragments.html -->
     <!DOCTYPE html>
<html xmlns:th="" lang="sk">
<html lang="en">
 <meta charset="UTF-8">

<!--fragment footer-->
<footer th:fragment="footer">
 <p>Footer: xxx</p>

<!--fragment comment-->

<div th:fragment="comments(AllComments)">

 <table class="comments">
         <th> Username </th>
         <th> Comment </th>
         <th> Commented On</th>
     <tr th:if="${AllComments.empty}">
         <td colspan="2"> No Comments Available </td>
     <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>



Just pass the variable to where you use the fragment:

<div th:replace="fragments/fragments :: comments(${AllComments})" />

Answered By – Wim Deblauwe

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published