在模版中綁定變量,通常的操作可能是在視圖中通過render 傳入到模版的上下文中,這樣非常簡單,不過在頁面較多出現(xiàn)該變量時(shí),就需要在每一個(gè)請求的視圖中做重復(fù)的查詢傳入,這樣不利于后期維護(hù)和問題分析。
所以很自然的就需要使用自定義的標(biāo)簽來解決重用的問題:
在頁面中引入變量通常是這樣的: {% xxx %}
在template中提供了三種標(biāo)簽分別是:
simple_tag 簡單標(biāo)簽
inclusion_tag 包含標(biāo)簽
assignment_tag 賦值標(biāo)簽
簡單標(biāo)簽:
在項(xiàng)目app中創(chuàng)建標(biāo)簽工具包, 如圖, blog是創(chuàng)建的app, templatetags是自定義標(biāo)簽的工具包

創(chuàng)建標(biāo)簽工具包
- 導(dǎo)入template
from django import template
fromblog.modelsimportPost,Category
- 實(shí)例化標(biāo)簽庫
register = template.Library()
- 自定義一個(gè)簡單標(biāo)簽
@register.simple_tag
def total_posts():
""" 自定義一個(gè)簡單標(biāo)簽"""
return Post.published.count()
- 在前臺模版中首先加載工具包,然后引用即可
{% load blog_tags %}
{% total_posts %}
包含標(biāo)簽
包含標(biāo)簽相較于簡單標(biāo)簽,加入了自定義內(nèi)容塊。
在template文件夾中創(chuàng)建文件名為 lasted_post.html 的文件
創(chuàng)建包含標(biāo)簽函數(shù),此處裝飾器中,變量名稱就是內(nèi)容塊的文件名,這樣,就可以將lasted_post 作為上下文傳入lasted_post.html中
@register.inclusion_tag('lasted_post.html')
def get_lasted_posts(count=3):
"""自定義包含標(biāo)簽"""
lasted_post = Post.published.order_by('-publish')[:count]
return {'lasted_post': lasted_post}
- lasted_post.html 內(nèi)容如下:
<ul>
{% for post in lasted_post %}
<li><a href="{{ post.get_absolute_url }}">{{ post.title }}</a></li>
{% endfor %}
</ul>
- 嵌入到模版中
{% get_lasted_posts 3 %}
賦值標(biāo)簽
包含標(biāo)簽的弊端是不夠靈活,而賦值標(biāo)簽則類似于通過視圖函數(shù)傳入變量,能實(shí)現(xiàn)最大限度的靈活。
實(shí)現(xiàn)分類標(biāo)簽方式如下:
@register.assignment_tag
def get_all_cate():
"""賦值標(biāo)簽"""
cate = Category.objects.all()
return cate
- 模版引用的方法和普通視圖傳遞的變量一樣
{% get_all_cate as cates %}
{% for cate in cates %}
<li><a href="?cate={{ cate.slug }}" title="{{ cate.name }}">{{ cate.name }}</a></li>
{% endfor %}