|
|
|
|
@ -1,30 +1,85 @@
|
|
|
|
|
#zyl:
|
|
|
|
|
|
|
|
|
|
from django import template
|
|
|
|
|
|
|
|
|
|
# 创建模板库实例,用于注册自定义模板标签
|
|
|
|
|
register = template.Library()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@register.simple_tag
|
|
|
|
|
def parse_commenttree(commentlist, comment):
|
|
|
|
|
"""获得当前评论子评论的列表
|
|
|
|
|
用法: {% parse_commenttree article_comments comment as childcomments %}
|
|
|
|
|
"""
|
|
|
|
|
递归获取指定评论的所有子评论(子孙评论)列表
|
|
|
|
|
采用深度优先遍历方式收集所有后代评论
|
|
|
|
|
|
|
|
|
|
模板中的用法:
|
|
|
|
|
{% parse_commenttree article_comments comment as childcomments %}
|
|
|
|
|
然后可以在模板中通过 {{ childcomments }} 使用返回的子评论列表
|
|
|
|
|
|
|
|
|
|
参数:
|
|
|
|
|
commentlist: QuerySet,包含所有评论的集合(通常在视图中查询并传入模板)
|
|
|
|
|
comment: Comment 对象,要查找其子评论的父评论
|
|
|
|
|
|
|
|
|
|
返回:
|
|
|
|
|
list: 包含所有子评论(及孙评论等)的扁平化列表,按深度优先顺序排列
|
|
|
|
|
"""
|
|
|
|
|
datas = []
|
|
|
|
|
|
|
|
|
|
def parse(c):
|
|
|
|
|
"""
|
|
|
|
|
内部递归函数,查找并收集指定评论的直接子评论及其所有后代
|
|
|
|
|
|
|
|
|
|
参数:
|
|
|
|
|
c: 当前正在处理的父评论对象
|
|
|
|
|
"""
|
|
|
|
|
# 从评论列表中筛选出:parent_comment 为当前评论 c 且已启用的子评论
|
|
|
|
|
childs = commentlist.filter(parent_comment=c, is_enable=True)
|
|
|
|
|
|
|
|
|
|
# 遍历每个子评论
|
|
|
|
|
for child in childs:
|
|
|
|
|
# 将子评论添加到结果列表
|
|
|
|
|
datas.append(child)
|
|
|
|
|
# 递归处理,查找该子评论的后代评论
|
|
|
|
|
parse(child)
|
|
|
|
|
|
|
|
|
|
# 从传入的根评论开始递归
|
|
|
|
|
parse(comment)
|
|
|
|
|
|
|
|
|
|
# 返回收集到的所有子评论列表
|
|
|
|
|
return datas
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@register.inclusion_tag('comments/tags/comment_item.html')
|
|
|
|
|
def show_comment_item(comment, ischild):
|
|
|
|
|
"""评论"""
|
|
|
|
|
"""
|
|
|
|
|
包含标签(inclusion tag):渲染单个评论项的 HTML 模板片段
|
|
|
|
|
|
|
|
|
|
模板中的用法:
|
|
|
|
|
{% show_comment_item comment_obj 0 %}
|
|
|
|
|
或
|
|
|
|
|
{% show_comment_item comment_obj 1 %}
|
|
|
|
|
|
|
|
|
|
参数:
|
|
|
|
|
comment: Comment 对象,要显示的具体评论
|
|
|
|
|
ischild: 布尔值或整数(0/1),表示该评论是否为子评论
|
|
|
|
|
通常使用布尔值 True/False,但模板中传入的可能是 0/1
|
|
|
|
|
|
|
|
|
|
功能:
|
|
|
|
|
1. 根据 ischild 参数计算评论的缩进深度(用于前端样式)
|
|
|
|
|
2. 将评论对象和深度值传递给指定的模板进行渲染
|
|
|
|
|
|
|
|
|
|
返回:
|
|
|
|
|
dict: 包含模板上下文变量的字典
|
|
|
|
|
- comment_item: 评论对象本身
|
|
|
|
|
- depth: 深度值(1 表示子评论,2 表示顶级评论)
|
|
|
|
|
深度值可用于控制评论的缩进层级或样式
|
|
|
|
|
"""
|
|
|
|
|
# 计算深度:如果是子评论 depth=1,否则 depth=2
|
|
|
|
|
# 这个逻辑通常用于控制评论的缩进层级,顶级评论缩进更多(或更少)以形成视觉层次
|
|
|
|
|
depth = 1 if ischild else 2
|
|
|
|
|
|
|
|
|
|
# 返回字典,作为评论项模板的上下文
|
|
|
|
|
return {
|
|
|
|
|
'comment_item': comment,
|
|
|
|
|
'depth': depth
|
|
|
|
|
}
|
|
|
|
|
'comment_item': comment, # 评论对象,在模板中可通过 comment_item 访问
|
|
|
|
|
'depth': depth # 深度值,在模板中可通过 depth 访问
|
|
|
|
|
}
|