Flask螺纹注释

2024-04-20 03:02:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在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程序如下所示:

^{pr2}$

和jinja模板我想递归地显示注释。在

{%- for item in comments recursive %}
<li>{{ item.content }}</li>
{%- if item.children -%}
<ul class="children">{{ loop(item.children) }}</ul>
{%- endif %}</li>
{%- endfor %}

在Jinja中,如何存储当前帖子的子级并递归地显示嵌套注释。在


Tags: answeriddateislicontentthisitem
1条回答
网友
1楼 · 发布于 2024-04-20 03:02:15

我在我的游戏Infinitroid的烧瓶网站的论坛上做了类似的事情,例如https://infinitroid.com/forum/posts/12

我基本上是在服务器端,使用每个注释的父id来确定一个整数depth或缩进级别:如果按主键排序,则后面的注释排在较早的注释之后,父注释应该已经在列表中。因此,您可以为没有父级的注释设置depth = 0,为有父级的注释设置parent.depth + 1(使用临时字典进行查找)。

设置您的CSS以根据标记嵌套级别缩进。然后,使用下面的算法进行显示。在我的例子中,我通过javascript显示注释(如果您感兴趣,可以在该页面上查看源代码),但是该算法在Jinja中也应该是可行的。

从深度=0开始。对于每条评论:

  • 如果删除深度级别,请为每个级别添加结束标记
  • 为此注释添加开始标记并增加深度级别
  • 显示评论正文
  • 在最后一条注释中,为任何剩余的深度级别添加结束标记

您可以将其构造为“带出口的循环”循环,以避免复制闭合深度级别部分。

相关问题 更多 >