Search code examples
javaspring-bootthymeleaf

springboot Thymeleaf adding varying List fields


I am using Thymeleaf for generating html file some content sharing purpose.

Below is the html template

    <html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Testing</title>
</head>
<body>
    <table>
        <tbody>
            <tr>
                <td>Message: </td>
                <td><p th:text="|${Id}|"> Id</p></td>
                <td><  th:text="|${userDetails}|"> </td>


            </tr>
        </tbody>
    </table>
</body>
</html>

and below is the code I tried generate different html tables or paragraph

   private static final String starttag= "<p><b>$$</b></p>";
    private static final String pretag= "<pre<$$</pre>";

    public String build(Message model) {
        Context context = new Context();
        context.setVariable("Id", model.getId());

        List<user> users = model.getUsers();

        StringBuilder userDetails = new StringBuilder("");
        for(user: users) {
            String getDepartment = starttag.replace("$$",user.getDepartment());
            userInfo = userInfo + pretag.replace("$$", "Name:"+ user.getName());

            userDetails.append(userInfo);
        }
        context.setVariable("userDetails", userDetails);
        return templateEngine.process("userTemplate", context);
    }


} 

but I am getting the result as below

<td><p>123 Id</p></td>
                <td> &lt;p&gt;&lt;b&gt;Computer Science &lt;/b&gt;&lt;/p&gt; Name:testuser1&lt;pre&lt;&lt;/pre&gt;</span> </td>

How to add the varying user list in html

I want like below

Testuser1

Computer Science

Testuser2

Electrical


Solution

  • You can pass directly the user object to the template:

    public String build(Message model) {
            model.setAttribute("Id", model.getId());
    
            List<user> users = model.getUsers();
            model.setAttribute("users", users);
    
            return "userTemplate";
        }
    

    Then access the field in the template with a for loop:

    <tr th:each="user: ${users}">
        <td th:text="${user.department}" />
        <td th:text="${user.name}" />
    </tr>
    

    This is a simple row, you can customize it with your own html adding it to the template. The point here is that you do not have to manage the html code in the controller class, you have only to prepare the model. In the html code you define your template.
    You can get additional information on this article on Baeldung, an example on this question on SO and also this question (is not your problem, but can help you to figure it out :) ).
    If is not enough clear, please comment the answer and I'll try to add some details.