【发布时间】:2014-10-07 09:32:12
【问题描述】:
我正在尝试使用 Jinja2 递归 for 循环打印出嵌套 cmets 列表。我遇到的问题是,在打印出一个完整的嵌套分支后,它又从一个嵌套的子分支开始,并从那里绘制另一个列表。
如果之前已经打印过,我想找到一种跳过迭代的方法。
我定义了以下 Flask 模型:
class Comment(db.Model):
"""Class containing comments to a post"""
__tablename__ = "comment"
id = db.Column(db.Integer, primary_key=True)
body = db.Column(db.String(255))
parent_id = db.Column(db.Integer, db.ForeignKey('comment.id'))
children = db.relationship("Comment")
def __init__(self, body=None, parent_id=None):
self.body = body
self.parent_id = parent_id
这会加载一些嵌套的 cmets:
comment = Comment(body="First Comment")
db.session.add(comment)
db.session.commit()
comment2 = Comment(body="Nested with First Comment", parent_id=comment.id)
db.session.add(comment2)
db.session.commit()
comment3 = Comment(body="Also nested with First Comment", parent_id=comment.id)
comment4 = Comment(body="Nested with the fist nested comment", parent_id=comment2.id)
db.session.add(comment3)
db.session.add(comment4)
db.session.commit()
这是相关的 Jinja2 模板:
<div class="row">
<ul class="media-list">
<li class="media">
{%- for comment in user.musician.comments recursive %}
<div class="media">
<span class="pull-left">
{{ comment.author.name }} said:
</span>
<div class="media-body">
<p>{{comment.body }}</p>
{% if comment.children %}
<!-- Children starts here -->
{{ loop(comment.children) }}
<!-- end of child -->
{% endif %}
</div>
</div>
{% endfor %}
</li>
</ul>
</div>
【问题讨论】:
标签: python recursion flask jinja2 adjacency-list