myblog_tag.py
#coding:utf-8
__author__ = ‘similarface‘from django import template register=template.Library() from ..models import Post @register.simple_tagdef total_posts(): ‘‘‘ 文章总数 :return:返回发布的文章总篇数 ‘‘‘ return Post.published.count()
模版:
{% load blog_tags %} {% load staticfiles %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>{% block title %}{% endblock %}</title> <link href="{% static "css/blog.css" %}" rel="stylesheet"> </head> <body> <div id="content"> {% block content %} {% endblock %} </div> <div id="siderbar"> <h2>我的博客</h2> <p>目前已写文章总数 {% total_posts %} .</p> </div> </body> </html>
看下面,哦,还是挺丑的
纳尼 这也太low了
go on add myblog_tag.py here:
@register.inclusion_tag(‘myblog/post/latest_posts.html‘) def show_latest_posts(count=5): ‘‘‘ 最新count篇文章 :param count: 文章的篇数 默认5篇 :return:最新count篇文章的对象 ‘‘‘ latest_posts=Post.published.order_by(‘-publish‘)[:count] return {‘latest_posts‘:latest_posts}
#myblog/post/latest_posts.html:
<ul> {% for post in latest_posts %} <li> <a href="{{ post.get_absolute_url }}">{{ post.title }}</a> </li> {% endfor %} </ul>
模版修改下:
<div id="siderbar"> <h2>我的博客</h2> <p>目前已写文章总数 {% total_posts %} .</p> <h3>最新文章</h3> {% show_latest_posts 3 %} </div>
哦 原来是个??。。。
哦 你再改改试试
#coding:utf-8 __author__ = ‘similarface‘ from django import template from django.db.models import Count register=template.Library() from ..models import Post @register.simple_tag() def total_posts(): ‘‘‘ 文章总数 :return:返回发布的文章总篇数 ‘‘‘ return Post.published.count() @register.inclusion_tag(‘myblog/post/latest_posts.html‘) def show_latest_posts(count=5): ‘‘‘ 最新count篇文章 :param count: 文章的篇数 默认5篇 :return:最新count篇文章的对象 ‘‘‘ latest_posts=Post.published.order_by(‘-publish‘)[:count] return {‘latest_posts‘:latest_posts} @register.assignment_tag def get_most_commented_posts(count=5): ‘‘‘ 返回评论最多的前count篇文章 :param count:默认为5 :return:返回评论最多的前count篇文章 ‘‘‘ return Post.published.annotate(total_comments=Count(‘comments‘)).order_by(‘-total_comments‘)[:count]
模版:
<div id="siderbar"> <h2>我的博客</h2> <p>目前已写文章总数 {% total_posts %} .</p> <h3>最新文章</h3> {% show_latest_posts 3 %} <h3>最受欢迎的文章</h3> {% get_most_commented_posts as most_commented_posts %} <ul> {% for post in most_commented_posts %} <li> <a href="{{ post.get_absoulte_url }}">{{ post.title }}</a> </li> {% endfor %} </ul> </div>
尼玛这。。。感觉记不住
时间: 2024-10-13 23:32:08