自定义过滤器filter和标签tag
filter 自定义过滤器
创建
在app下创建一个名为templatetags的python包(名称不能变)
在templatetags 创建py文件 自定义名称 my_tags.py(名称自定义)
在py文件中写入:
from django import template register = template.Library() # register也不能变
写函数+装饰器
@register.filter def add_xx(value, arg): # 最多有两个 return '{}-{}'.format(value, arg)
使用
使用
{% load my_tags %} {{ 'alex'|add_xx:'dsb' }}
simpletag 标签(返回内容自定义)
和自定义filter类似,只不过接收更灵活的参数。
定义注册simple tag
@register.simple_tag(name="plus") def plus(a, b, c): return "{} + {} + {}".format(a, b, c)
使用自定义simple tag
{% load app01_demo %} {# simple tag #} {% plus "1" "2" "abc" %}
inclusion_tag 标签(函数内返回内容必须是一个字典,第三个文件去渲染,然后代码段返回给html文件)
示例:
- templatetags/my_inclusion.py
from django import template register = template.Library() @register.inclusion_tag('result.html') def show_results(n): n = 1 if n < 1 else int(n) data = ["第{}项".format(i) for i in range(1, n+1)] return {"data": data}
- templates/result.html
<ul> {% for choice in data %} <li>{{ choice }}</li> {% endfor %} </ul>
- templates/index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="x-ua-compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>inclusion_tag test</title> </head> <body> {% load my_inclusion %} {% show_results 10 %} </body> </html>