thymeleaf iteration on a list

sebcarotte

I'm struggling with looping on a list using thymeleaf. I've these two classes :

public class Contact {
    private String firstname;
    private String lastname;
    private String email;
    private String phone;

public class ContactForm {  
    private List<Contact> contacts;

The following controller:

@RequestMapping(value = "/get", method = RequestMethod.GET)
public ModelAndView get() {

    ContactForm contactForm = new ContactForm();
    contactForm.setContacts(Application.contacts);

    return new ModelAndView("add_contact" , "contactForm", contactForm);
}

And the view :

<form method="post" action="save.html" th:action="@{/save}"
    th:object="${contactForm}" modelattribute="contactForm">
    <table>
        <c:out value="${contactForm.contacts.size()}" />
        <tr th:each="contact : ${contactForm.contacts}">
            <td><input type="text" name="field1"
                th:field="${contact.firstname}" /></td>
            <td><input type="text" name="field2"
                th:field="${contact.lastname}" /></td>
            <td><input type="text" name="field3 "
                th:field="${contact.email}" /></td>
            <td><input type="text" name="field4"
                th:field="${contact.phone}" /></td>
        </tr>

        </tbody>
    </table>
    <br>
    <input value="Save" type="submit">
</form>

The Application.contact is a List of Contacts with 4 elements inside. The result on the browser for the line

<c:out value="${contactForm.contacts.size()}" />

is a "4" printed on the page so the object and the 4 elements are successfully passed to the view. Unfortunately it never goes into the th:each and so nothing is printed inside. What am I doing wrong here ?

Thanks for your time

MystyxMac

Looks like Thymeleaf is not properly configured.

With Spring Boot and Thymeleaf you need at least the following dependecies in your pom to let Spring Boot automatically configure Thymeleaf:

<dependency> 
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related