在模板的编写过程中,我们可以自定义模板标签
并在模板中进行任何地方进行方便的使用
(一)模板标签的创建
包括两大步骤:
- 编写模板标签的py文件,在其中定义模板标签函数
- 编写标签对应的模板,对标签函数的数据进行渲染
1.编写模板标签的py文件,在其中定义模板标签函数
在app路径下创建一个py包,并新建python文件,在里面定义模板标签函数
在blog路径下新建名为templatetags的python包,并在其下新建blog_extras.py文件,templatetags包应该包含俩个文件:init.py和blog_extras.py。目录结构为:
blog_extras.py文件:
from django import template
from ..models import Post, Category, Tag
# 用于注册模板标签和过滤器的对象
register = template.Library()
# register.inclusion_tag装饰器:
# 将show_recent_posts_tag函数注册为inclusion_tag类型的模板标签
@register.inclusion_tag('blog/inclusions/_recent_posts.html', takes_context=True)
def show_recent_posts_tag(context, num=5):
return {
'recent_post_list': Post.objects.all().order_by('-created_time')[:num], #返回查询结果的前5个文章
}
@register.inclusion_tag('blog/inclusions/_archives.html', takes_context=True)
def show_archives(context):
return {
"date_list":Post.objects.dates('created_time','month', order='DESC'),
}
@register.inclusion_tag('blog/inclusions/_categories.html', takes_context=True)
def show_categories(context):
return {
'category_list':Category.objects.all(),
}
@register.inclusion_tag('blog/inclusions/_tag.html', takes_context=True)
def show_tags(context):
return {
'tag_list':Tag.objects.all(),
}
其中,register = template.Library()
是用于模板标签注册的对象。
模板标签注册,使用register对象的inclusion_tag装饰器@register.inclusion_tag(path,takes_context)
将普通函数注册为inclusion_tag类型的模板标签。
- 其中
path
为模板标签函数渲染的模板 takes_context=True
可以传入调用模板的上下文对象
也正是因为设置了takes_context=True
,标签函数中必须要有参数context。
注意: 标签函数的作用是向标签模板中传入数据。return的数据类型必须是字典
。
2.编写标签对应的模板
新建inclusions模板包,目录如下:
其中_archives.html等文件为包下的标签模板
以_archives.html为例
<div class="widget widget-archives">
<h3 class="widget-title">归档</h3>
<ul>
{% for date in date_list %}
<li>
<a href="#">{{ date.year }} 年 {{ date.month }} 月</a>
</li>
{% empty %}
暂无归档!
{% endfor %}
</ul>
</div>
将标签函数show_archives返回的数据date_list进行遍历后展示。
(二)模板标签的使用
1. 加载标签包
在需要使用模板标签的模板的文件头加载标签包,即包含标签函数的py文件
<!DOCTYPE html>
<html>
{% load static %}
{% load blog_extras %}
<head>
...
2. 在任意地方使用
在需要的地方,通过{% 函数名 %}方式进行模板标签的使用。
{% show_recent_posts_tag 2%}
{% show_archives %}
{% show_categories %}
{% show_tags %}
其中2表示可以向模板标签传参。