问题描述
限时送ChatGPT账号..我在会话中有一个对象,例如一个部门,这个部门有孩子.我得到了它的孩子的列表,现在我想在这个列表中添加这个部门对象.这在服务器端非常简单,但它是可以在 thymeleaf 中做到这一点.
解决方案是的,可以在 Thymeleaf 中完成,因为它使用 对象图导航语言 用于评估表达式值 - ${...}
块的内容.您可以正常访问模型对象上的公共方法,因此调用 boolean List#add(E e)
方法有效.
但正如其他人提到的这不是一个好主意,您应该重新设计您的应用程序以在控制器中填充您的模型.另一方面,如果您需要进行一些讨厌的黑客攻击或只是玩玩,请参见下面的示例.它使用 th:text
来评估添加到列表,然后使用 th:remove
来清理标签并且不留下任何痕迹.
部门模型类:
公开课系{私人字符串名称;公共部门(字符串名称){this.name = 名称;}公共字符串 getName() {返回名称;}公共无效集名称(字符串名称){this.name = 名称;}}
模型中的数据(例如会话)
列表<部门>孩子 = 新的 ArrayList<>();children.add(new Department("Department 1"));children.add(new Department("Department 2"));//在模型中作为*部门*变量部门部门=新部门(主要部门");部门.setChildren(儿童);
Thymeleaf 模板:
<html xmlns:th="http://www.thymeleaf"><头>头部><身体><h1>之前</h1><ul><li th:each="child : ${department.children}" th:text="${child.name}"></li><!--/* 一个讨厌的把戏来了!*/--><div th:text="${department.children.add(department)}" th:remove="all"></div><h1>结果</h1><ul><li th:each="child : ${department.children}" th:text="${child.name}"></li>
发布评论