from django import template
register = template.Library()
# 自定义过滤器
@register.filter(name='my_filter')
def index(a, b):
return a*b
# 自定义标签:
@register.simple_tag
def plus(a, b, c):
return a+b+c
{% load mine %} <!-- 要使用自定义过滤器和标签,需要先加载自己定义的文件 -->
{{ 9|my_filter:11 }} <!-- 使用自定义过滤器,注意这里需要用name的值作为使用方法 -->
{% my_tag 1 2 3 %} <!-- 使用自定义标签,注意这里需要用name的值作为使用方法 -->
# mine.py文件 创建inclusion_tag
from app01 import models
from django import template
register = template.Library()
@register.inclusion_tag('inclusion_t_test.html', name='my_inclusion')
def func():
book_list = models.Book.objects.all()
return {'list': book_list}
#将book_list的QuerySet对象列表传进inclusion_t_test.html文件
<!-- inclusion_t_test.html文件,被导入的html文件-->
<table>
<thead>
<tr>
<th>id</th>
<th>title</th>
<th>price</th>
</tr>
</thead>
<tbody>
{% for obj in list %}
<tr>
<td>{{ obj.id }}</td>
<td>{{ obj.title }}</td>
<td>{{ obj.price }}</td>
</tr>
{% endfor %}
</tbody>
</table>
{% load mine %} <!-- 必须要先加载创建标签的文件-->
{% my_inclusion %} <!-- 调用inclusion_t_test.html页面文件,这里使用该标签的name来调用-->