フラスティにネストされたコメントを表示したいと思います。私はMongoDBのを使用して、私の文書構造は、このようなものです:私は再帰的にコメントを表示したいと思いフラスコスレッドのコメント
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)
そして神社テンプレート:
{"_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プログラムは次のようになります。
{%- for item in comments recursive %}
<li>{{ item.content }}</li>
{%- if item.children -%}
<ul class="children">{{ loop(item.children) }}</ul>
{%- endif %}</li>
{%- endfor %}
現在の投稿の子供を保存し、ネストされたコメントをJinjaに再帰的に表示する方法。