1.在应用下创建目录templatetags(必须是该应用名)
2.在templatetags目录下创建自定义标签文件tags.py和自定义过滤器文件filters.py
tags.py
from django import template from django.utils.html import format_html register = template.Library() # 自定义标签 @register.simple_tag def my_add(arg_01, arg_02): res_add = arg_01 + arg_02 return res_add @register.simple_tag def my_reduce(arg_01, arg_02): res_reduce = arg_01 - arg_02 return res_reduce @register.simple_tag def my_multiply(arg_01, arg_02): res_multiply = arg_01 * arg_02 return res_multiply @register.simple_tag def my_division(arg_01, arg_02): res_division = arg_01 / arg_02 return res_division if __name__ == '__main__': res = my_add(9, 9) print(res)
fliters.py
from django import template register = template.Library() # 自定义过滤器 @register.filter def hello(name): sayhello = 'Hi' + ' ' + name return sayhello if __name__ == '__main__': res = say_hello('mary') print(res)
视图函数views.py
def filter_tag(request): data = {'name': 'mary', 'country': 'usa', 'age': 18, 'special_product': ['香菇', '酸菜', '腊肉']} return render(request, 'filtertag.html', data)
在页面就可以使用了,自定义的标签和过滤器使用前需要导入 {% load 自定义文件 %}
filtertag.py
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>自定义标签和过滤器</title> </head> <body> {{ country|lower|upper }} <br> {{ age|add:5 }} <br> {{ like|default:'not data' }} <br> {{ special_product|join:'=>' }} <br> {% load filters %} {{ name|hello }} <br> {% load tags %} {% my_add 3 9 %} <br> {% my_division 9 3 %} </body> </html>