建立DJANGO的自定义TAG

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层展示

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值