Reputation: 639
Currently i'm doing website with newsletter posting. I want to post and show comments under every post.
MY POST
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>
Upvotes: 0
Views: 963
Reputation: 20487
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>
Upvotes: 1