Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add an object in list using thymeleaf?

Tags:

thymeleaf

I have an object in session for example of a department and this department have children.I got the list of its children, now i want to add this department object in this list.This is very simple at server side but is it possible to do this in thymeleaf.

like image 952
kamal Avatar asked Nov 01 '22 12:11

kamal


1 Answers

Yes it is possible to do it in Thymeleaf since it's using Object-Graph Navigation Language for evaluating expression values - content of ${...} block. You can access public methods normally on your model object so calling boolean List#add(E e) method works.

But as others mentioned it's NOT really good idea and you should redesign your application to fill your model in controller. On the other side if you need to make some nasty hack or just playing around see example below. It's using th:text to evaluate adding to list then th:remove to clean tag and leave no trace.

Department Model class:

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;
    }

}

Data in model (eg. session)

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);

Thymeleaf template:

<!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>

Before

  • Department 1
  • Department 2

Result

  • Department 1
  • Department 2
  • Main Department

P.S. Spring Expression Language is used with Spring integration but for this example it makes no difference.

like image 94
michal.kreuzman Avatar answered Dec 04 '22 07:12

michal.kreuzman