我想在Flask中显示嵌套的注释。我使用MongoDb,我的文档结构是这样的:
{"_id":16,"content":"This is first answer.","discussion_id":1,
"posted":{"$date":"2017-10-26T19:19:05.174Z"}}
{"_id":17,"content":"This is second answer.","discussion_id":1,
"posted":{"$date":"2017-10-26T19:19:27.325Z"}}
{"_id":18,"content":"This is third answer.","discussion_id":1,
"posted":{"$date":"2017-10-26T19:20:00.126Z"}}
{"_id":19,"content":"This is fourth answer. This answer's parent should be second.","discussion_id":1,
"posted":{"$date":"2017-10-26T19:21:28.206Z"},"parentid":2}
{"_id":20,"content":"Fifth answer whose parent should be fourth.","discussion_id":1,
"posted":{"$date":"2017-10-26T19:22:11.393Z"},"parentid":4}
测试python程序如下所示:
from flask import render_template
from flask import Flask
from flask_pymongo import PyMongo
app = Flask(__name__)
app.config['MONGO_DBNAME'] = 'programming'
app.config['MONGO_URI'] = 'mongodb://localhost:27017/programming'
app.config['JSON_AS_ASCII'] = False
mongo = PyMongo(app)
@app.route('/')
def index():
table = mongo.db.comments
commentList = table.find({'discussion_id' : 1})
comments = []
for comment in commentList:
comments.append({'commentnumber' : comment['_id'], 'date' : comment['posted'], 'content' : comment['content']})
result = mongo.db.comments.find_one( { '_id' : comment['_id'] , "parentid": { '$exists': True, '$ne': False } })
if (result):
comments.append({ 'parent' : comment['parentid'] })
print("Parent comment ", comment['parentid'])
return render_template('index.html', comments=comments)
if __name__ == "__main__":
app.run(debug=True)
jinja模板我想以递归方式显示评论。
{%- for item in comments recursive %}
<li>{{ item.content }}</li>
{%- if item.children -%}
<ul class="children">{{ loop(item.children) }}</ul>
{%- endif %}</li>
{%- endfor %}
如何存储当前帖子的子节点并在Jinja中递归显示嵌套注释。
答案 0 :(得分:2)
我在我的游戏Infinitroid的Flask网站的论坛上做了类似的事情,例如: https://infinitroid.com/forum/posts/12
我基本上做的是,在服务器端,使用每个注释的parent-id来确定整数depth
或缩进级别:如果按主键排序,则后面的注释在eariler之后,并且父母应该已经在列表中。因此,您可以为没有父级的注释设置depth = 0
,为父级的注释设置parent.depth + 1
(使用临时字典进行查找)。
根据标记嵌套级别设置CSS缩进。然后,使用下面的算法进行显示。在我的情况下,我通过javascript显示评论(如果你很好奇,你可以查看该页面上的来源),但算法也应该在Jinja中可行。
从深度= 0开始。对于每条评论:
您可以将此结构化为&#34;循环,退出&#34;循环以避免重复关闭深度级别部分。