从数据库中取出本篇博客的所有评论
使用python语句将评论整理成具有层级关系的列表
typename=request.POST.get('typename')
comment_list = models.comment.objects.filter(article_id=int(typename)).values("id", "content",
"user__nickname", "parent_id_id")
comment_dict = {}
for item in comment_list:
item["child"] = []
comment_dict[item['id']] = item
comment = []
for item in comment_list:
pid = item["parent_id_id"]
if pid:
comment_dict[pid]["child"].append(item)
else:
comment.append(item)
方式一:
后台生成html字符串(递归函数)
def comment_tree(comment_list):
# [{'child': [{'child': [{'child': [], 'user__nickname': 'egon', 'content': '哪里不好啊', 'create_time': None, 'id': 3, 'parent_id': 2}],
# 'user__nickname': 'sever', 'content': '扯淡', 'create_time': None, 'id': 2, 'parent_id': 1}],
# 'user__nickname': 'egon', 'content': '写的太好了', 'create_time': None, 'id': 1, 'parent_id': None},
# {'child': [], 'user__nickname': 'root', 'content': '写的不错', 'create_time': None, 'id': 4, 'parent_id': None},
# {'child': [], 'user__nickname': 'alex', 'content': '我写的真好', 'create_time': None, 'id': 5, 'parent_id': None}]
comment_str="<div class='comment'>"
for row in comment_list:
tpl="<div class='content'>%s:%s --- %s</div>"%(row['user__nickname'],row['content'],row['create_time'])
comment_str += tpl
if row['child']:
child_str=comment_tree(row['child'])
comment_str += child_str
comment_str += '</div>'
return comment_str
方式二:前端生成
页面加载完成之后发送ajax请求
js 函数递归
字符串格式化
$.ajax({
url:'/comment.html',
data:{'typename':{{ article.article.aid }},'csrfmiddlewaretoken':'{{ csrf_token }}'},
type:'post',
dataType:'JSON',
success:function (data) {
var comment=commentTree(data);
$('.commentarea').append(comment)
}
});
{# var nn =new Date;#}
{# nn.getDate() ;#}
/*
前端 调用对象方法时,是通过调用类的propotype中的方法
正则表达式:/\w+/g
字符串replace
''.replace(/(\w+)/g,function(k,kk){return 11})
*/
String.prototype.Format=function(arg){
/*
this 当前字符串
arg format方法传入的参数{key:value}
return 格式化之后获取的新内容
*/
var temp=this.replace(/\{(\w+)\}/g,function(k,kk){
return arg[kk];
});
return temp;
};
function commentTree(comment_list){
var comment_str="<div class='comment'>";
$.each(comment_list,function(k,row){
var temp="<div class='content'>{user}{content}---{time}</div>";
var temp1=temp.Format({user:row.user__nickname,content:row.content,time:row.create_time});
comment_str += temp1;
if(row.child.length>0){
comment_str += commentTree(row.child);
}
});
comment_str += "</div>";
return comment_str
}
来源:https://www.cnblogs.com/liuguniang/p/7233071.html