2017-10-26 9 views
1

フラスティにネストされたコメントを表示したいと思います。私は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に再帰的に表示する方法。

答えて

1

私のゲームInfinitroidのFlaskサイトのフォーラムで、同様のことをしました。 https://infinitroid.com/forum/posts/12

私が基本的にしたことは、各コメントの親IDを使用して整数depthまたはインデントレベルを決定することです。プライマリキーで並べ替えると、後のコメントはイヤーラーのものになります。親はすでにリストに登録されているはずです。したがって、親なしのコメントの場合はdepth = 0、親のあるコメントの場合はparent.depth + 1に設定することができます(参照用の一時的な辞書を使用)。

タグのネストレベルに基づいてインデントするようにCSSを設定します。次に、以下のアルゴリズムを使用して表示します。私の場合、javascriptを使ってコメントを表示します(興味があるなら、そのページのソースを見ることができます)が、アルゴリズムはJinjaでも実行可能でなければなりません。

深度= 0で始まります。各コメントの場合:深さレベルを落とす場合

  • 、レベルごとに終了タグを追加
  • が最後にコメント本体
  • を表示するには、このコメントの開始タグと増分深さレベル
  • を追加落とし残りの深度レベルの終了タグを追加する

閉じる深度レベルの部分が複製されないように、これを「ループ付きのループ」ループとして構成できます。