|
|
|
|
@ -1,30 +1,46 @@
|
|
|
|
|
from django import template
|
|
|
|
|
|
|
|
|
|
register = template.Library()
|
|
|
|
|
# gst: 注册模板标签库,使自定义标签可在模板中使用
|
|
|
|
|
register = template.Library()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@register.simple_tag
|
|
|
|
|
def parse_commenttree(commentlist, comment):
|
|
|
|
|
"""获得当前评论子评论的列表
|
|
|
|
|
用法: {% parse_commenttree article_comments comment as childcomments %}
|
|
|
|
|
"""
|
|
|
|
|
gst: 定义simple_tag,用于获取当前评论的所有子评论列表(递归遍历)
|
|
|
|
|
用法: {% parse_commenttree article_comments comment as childcomments %}
|
|
|
|
|
:param commentlist: 评论查询集(需包含所有待筛选的评论)
|
|
|
|
|
:param comment: 父评论对象,以此为根节点查找子评论
|
|
|
|
|
:return: 子评论列表(包含多级嵌套的子评论)
|
|
|
|
|
"""
|
|
|
|
|
datas = []
|
|
|
|
|
|
|
|
|
|
def parse(c):
|
|
|
|
|
"""
|
|
|
|
|
gst: 递归函数,用于遍历父评论的所有子评论并加入结果列表
|
|
|
|
|
:param c: 当前父评论对象
|
|
|
|
|
"""
|
|
|
|
|
# 筛选出当前父评论的有效子评论(is_enable=True)
|
|
|
|
|
childs = commentlist.filter(parent_comment=c, is_enable=True)
|
|
|
|
|
for child in childs:
|
|
|
|
|
datas.append(child)
|
|
|
|
|
parse(child)
|
|
|
|
|
datas.append(child) # 将子评论加入结果列表
|
|
|
|
|
parse(child) # 递归遍历该子评论的子评论
|
|
|
|
|
|
|
|
|
|
parse(comment)
|
|
|
|
|
return datas
|
|
|
|
|
parse(comment) # 从传入的comment开始递归解析
|
|
|
|
|
return datas
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@register.inclusion_tag('comments/tags/comment_item.html')
|
|
|
|
|
def show_comment_item(comment, ischild):
|
|
|
|
|
"""评论"""
|
|
|
|
|
depth = 1 if ischild else 2
|
|
|
|
|
"""
|
|
|
|
|
gst: 定义inclusion_tag,用于渲染评论项模板(区分父子评论的显示层级)
|
|
|
|
|
:param comment: 要渲染的评论对象
|
|
|
|
|
:param ischild: 是否为子评论(布尔值)
|
|
|
|
|
:return: 模板上下文,包含评论对象和显示层级
|
|
|
|
|
"""
|
|
|
|
|
# 根据是否为子评论设置深度(父评论深度为2,子评论深度为1)
|
|
|
|
|
depth = 1 if ischild else 2
|
|
|
|
|
return {
|
|
|
|
|
'comment_item': comment,
|
|
|
|
|
'depth': depth
|
|
|
|
|
}
|
|
|
|
|
'comment_item': comment, # 传递评论对象到模板
|
|
|
|
|
'depth': depth # 传递显示层级到模板
|
|
|
|
|
}
|