如何使用thymeleaf在列表中添加对象?

时间:2013-10-18 11:35:55

标签: thymeleaf

我在会话中有一个对象,例如一个部门,这个部门有子。我得到了它的子列表,现在我想在这个列表中添加这个部门对象。这在服务器端非常简单,但是它可以在百里香中做到这一点。

2 个答案:

答案 0 :(得分:1)

是的,可以在Thymeleaf中进行,因为它使用Object-Graph Navigation Language来评估表达式值 - ${...}块的内容。您可以在模型对象上正常访问公共方法,因此调用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);

Thymeleaf模板:

<!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
  •   
  • 主要部门
  •   

P.S。 Spring Expression Language与Spring集成一起使用,但对于此示例,它没有任何区别。

答案 1 :(得分:0)

这就像在返回值之前在getXXXX方法中设置一个值。它不符合模式。在Controller或Controller中进行数据操作以委托给其他人,但不在视图中。

相关问题