How to add an object to the list using thymeleaf?

I have an object in a session, for example, in a department, and this department has children.I got a list of my children, now I want to add this department object to this list. It is very simple on the server side, but it is possible to do it in the timeline.

+4
source share
2 answers

Yes, it is possible to do this in Thymeleaf, because it uses the Object-GUI navigation language to evaluate expression values ​​— the contents of the block ${...}, you can access public methods, usually on your model object, therefore the method works boolean List#add(E e).

, , , , . , - , . . th:text , th:remove .

:

public class Department {

    private String name;

    public Department(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

(, )

List<Department> children = new ArrayList<>();
children.add(new Department("Department 1"));
children.add(new Department("Department 2"));

// In model as *department* variable
Department department = new Department("Main Department");
department.setChildren(children);

:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
</head>
    <body>
        <h1>Before</h1>
        <ul>
           <li th:each="child : ${department.children}" th:text="${child.name}"></li>
        </ul>

        <!--/* Here comes a nasty trick! */-->
        <div th:text="${department.children.add(department)}" th:remove="all"></div>

        <h1>Result</h1>
        <ul>
           <li th:each="child : ${department.children}" th:text="${child.name}"></li>
        </ul>
    </body>
</html>

  • 1
  • 2

  • 1
  • 2

PS Spring Spring, .

+1

getXXXX . . , - , .

0

All Articles