java - 如何在百里香中动态创建多个嵌套对象
问题描述
目前我正在做网站发布时事通讯。我想在每个帖子下发布和显示评论。
我的帖子
- 第一条评论
- 对第一条评论的评论
- 对第二条评论的评论-依此类推...
- 对第一条评论的评论
- 第二条评论
- 第三条评论
我知道如何在具有一级嵌套的循环中动态创建元素。但是我怎样才能创建多个嵌套?
例如我可以创建评论:
<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>
解决方案
我认为您必须使用 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>