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

2024-03-26

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


是的,可以在 Thymeleaf 中执行此操作,因为它使用对象图导航语言 https://commons.apache.org/proper/commons-ognl/用于评估表达式值 - 的内容${...}堵塞。您可以正常访问模型对象上的公共方法,因此调用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>

Before

  • 部门1
  • 部门2

Result

  • 部门1
  • 部门2
  • 主要部门

P.S. Spring 表达语言 http://docs.spring.io/spring-framework/docs/current/spring-framework-reference/html/expressions.html与 Spring 集成一起使用,但对于本示例来说没有什么区别。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 thymeleaf 在列表中添加对象? 的相关文章

随机推荐