DJANGO的TAG分为三类:
• simple_tag : Processes the data and returns a string
• inclusion_tag : Processes the data and returns a rendered template
• assignment_tag : Processes the data and sets a variable in the context
blog_tags.py
from django import template register = template.Library() from ..models import Post from django.db.models import Count @register.simple_tag def total_posts(): return Post.published.count() @register.inclusion_tag('blog/post/latest_posts.html') def show_latest_posts(count=5): latest_posts = Post.published.order_by('-publish')[:count] return {'latest_posts': latest_posts} @register.assignment_tag def get_most_commented_posts(count=5): return Post.published.annotate(total_comments=Count('comments')).order_by('-total_comments')[:count]
latest_posts.html
<ul> {% for post in latest_posts %} <li> <a href="{{ post.get_absolute_url}}">{{ post.title }}</a> </li> {% endfor %} </ul>
base.html
<div id="sidebar"> <h2>My blog</h2> <p>This is my blog. I've written {% total_posts %} posts so far.</p> <h3>Latest posts</h3> {% show_latest_posts 3 %} <h3>Most commented post</h3> {% get_most_commented_posts as most_commented_posts%} <ul> {% for post in most_commented_posts %} <li> <a href="{{ post.get_absolute_url }}">{{ post.title }}</a> </li> {% endfor %} </ul> </div>
无css层展示