如何在百里香中动态创建多个嵌套对象

时间:2019-05-29 11:24:56

标签: java spring spring-mvc thymeleaf

目前,我正在发布新闻简报的网站。我想在每个帖子下发布并显示评论。

我的帖子

  • 第一则评论
    • 对第一条评论的评论
      • 对第二条评论的评论 -等等...
  • 第二条评论
  • 第三条评论

我知道如何在具有一级嵌套的循环中动态创建元素。但是如何创建多个嵌套?

例如,我可以创建评论:

<div class='comments' th:each="comment : ${comments}">
  <div class='comment' th:text='comment'/>
</div>

如何创建多个嵌套?

<div class='comments' th:each="comment : ${comments}">
  <div class='comment' th:text='comment'>
      <div class='comment' here comment to comment/>
          etc..
  </div>
</div>

1 个答案:

答案 0 :(得分:1)

我认为您必须使用fragments执行此操作。例如,使用这样的对象:

对象

class Comment {
    private String text;
    private List<Comment> children = new ArrayList<>();

    public Comment(String text, Comment... children) {
        this.text = text;
        this.children.addAll(Arrays.asList(children));
    }

    public String getText() {return text;}
    public void setText(String text) {this.text = text;}

    public List<Comment> getChildren() {return children;}
    public void setChildren(List<Comment> children) {this.children = children;}
}

控制器:

List<Comment> comments = new ArrayList<>();
comments.add(new Comment("hello", new Comment("nooooo")));
comments.add(new Comment("it's another comment", new Comment("again", new Comment("yeah!"))));
comments.add(new Comment("whoopity doo"));
model.put("comments", comments);

您可以输出带有以下片段的嵌套注释链:

<th:block th:each="comment: ${comments}">
    <div th:replace="template :: comments(${comment})" />
</th:block>

<th:block th:if="${false}">
    <ul th:fragment="comments(comment)">
        <li>
            <div th:text="${comment.text}" />

            <th:block th:unless="${#lists.isEmpty(comment.children)}" th:each="child: ${comment.children}">
                <div th:replace="template :: comments(${child})" />
            </th:block>
        </li>
    </ul>
</th:block>
相关问题