简体   繁体   English

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

[英]How to dynamically create multiple nested objects in thymeleaf

Currently i'm doing website with newsletter posting. 目前,我正在发布新闻通讯的网站。 I want to post and show comments under every post. 我想在每个帖子下发布并显示评论。

MY POST 我的帖子

  • first comment 第一条评论
    • comments to first comment 评论到第一个评论
      • comments to second comment -so on... 评论到第二评论-等等...
  • second comment 第二条评论
  • third comment 第三条评论

I know how to dynamically create elements in a loop with one level of nesting. 我知道如何在具有一级嵌套的循环中动态创建元素。 But how can i create multiple nesting? 但是如何创建多个嵌套?

For example I can create comments: 例如,我可以创建注释:

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

How can I create multiple nesting? 如何创建多个嵌套?

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

I think you'll have to do this with fragments . 我认为您必须使用片段进行此操作。 For example, with an object like this: 例如,使用这样的对象:

Objects 对象

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;}
}

Controller: 控制器:

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);

You can output a chain of nested comments with fragments like this: 您可以输出带有片段的嵌套注释链,如下所示:

<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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM