gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 21:17:31 26 4
gpt4 key购买 nike

我在 session 中有一个对象,例如一个部门,这个部门有 child 。我得到了它的 child 的列表,现在我想在这个列表中添加这个部门对象。这在服务器端非常简单,但可以做到这个在 thymeleaf 中。

最佳答案

是的,可以在 Thymeleaf 中执行此操作,因为它使用 Object-Graph Navigation Language用于评估表达式值 - ${...} 的内容堵塞。您可以在模型对象上正常访问公共(public)方法,因此调用 boolean List#add(E e)方法有效。

但正如其他人提到的 这不是一个好主意您应该重新设计您的应用程序以将您的模型填充到 Controller 中。另一方面,如果您需要进行一些讨厌的 hack 或只是玩玩,请参阅下面的示例。它正在使用 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;
}

}

模型中的数据(例如 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 模板:
<!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


附言 Spring Expression Language与 Spring 集成一起使用,但对于此示例,它没有区别。

关于thymeleaf - 如何使用 thymeleaf 在列表中添加对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19448731/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com