自定义标签和过滤器

自定义标签和过滤器

自定义过滤器

1. app应用文件夹中创建一个templatetags文件件,必须是这个名字
2. templatetags文件夹中创建一个 xx.py文件,文件名字随便起

3. 创建自定义过滤器
    from django import template

    register = template.Library()  #register固定的名字,注册器

    # @register.filter
    # def oo(v1,v2):  #不带参数的过滤器
    #     s = v1 + 'xxoo'

    #     return s

    @register.filter
    def oo(v1,v2):  #带参数的过滤器
        s = v1 + v2
        return s
    
4. 使用  html文件中  {% load 文件名 %} 
	{% load xx %}
    {{ values|oo }} -- 无参数
    {{ values|oo:'asdf' }} -- 有参数

5. 注意:参数最多两个


自定义标签
1. app应用文件夹中创建一个templatetags文件件,必须是这个名字
2. templatetags文件夹中创建一个 xx.py文件,文件名字随便起
3. 创建自定义标签
	@register.simple_tag
	def mytag(v1,v2,v3):  
    	s = v1 + '和B哥' + v2 + v3
    	return s

4.使用
	{% load xx %}
	{% mytag s1 '和相玺' '和大壮' %}  
5. #可以传多个参数


inclusion_tag

1. app应用文件夹中创建一个templatetags文件件,必须是这个名字
2. templatetags文件夹中创建一个 xx.py文件,文件名字随便起
3. 创建自定义inclusion_tag
	@register.inclusion_tag('inclusiontag.html')
    def func(v1):

        return {'oo':v1}
4. func的return数据,传给了inclusiontag.html,作为模板渲染的数据,将inclusiontag.html渲染好之后,作为一个组件,生成到调用这个func的地方
5. 使用
	{% load xx %}
	{% func l1 %}


原文地址:https://www.cnblogs.com/wyh0717/p/13555586.html