作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
目前我正在制作发布时事通讯的网站。我想在每个帖子下发布并显示评论。
我的帖子
我知道如何在具有一层嵌套的循环中动态创建元素。但如何创建多重嵌套?
例如,我可以创建评论:
<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;}
}
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);
您可以输出带有如下片段的嵌套注释链:
<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>
关于java - 如何在thymeleaf中动态创建多个嵌套对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56359485/
我是一名优秀的程序员,十分优秀!