自定义过滤器与自定义标签

模板语言自带的tag和过滤器,在某些情况下还不能满足我的功能需求,例如无法实现递归显示需求等,可以自定义fifter和tag;就像Python内置函数和自定义函数关系;

一.  自定义过滤器

    基于一般过滤器,自定义过滤器语法相同,方式一样

  (1)view中一般过滤器通过render传过参数date:

def test(request):

    return render(request,'test.html',{'date':datetime.datetime.now(),)

  html中

{{ date|date:'Y-m-d' }}

  以上为基本过滤器

   (2)自定义过滤器:

  

    通过render传过去参数需要复杂的处理,得到一个结果,不在是如"Y-m-d"这样的简单处理,那么就需要自定义过滤器来(本质就是自定义一个处理函数,调用过来处理数据).

    步骤:(1) 在app01(应用)中创建templatetags模块(模块名只能是templatetags)

      (2) 在templatetags下创建任意 .py 文件,如:mytags.py

      (3) 在py文件导入

                      from django import template
                      from django.utils.safestring import mark_safe
     (4)写register,用register.filter装饰到函数上(myreplace),然后就可以编写函数的功能了

from django import template
from django.utils.safestring import mark_safe
register = template.Library() #创建注册器 @register.filter #注册器以装饰器的形式放到函数上端 def myreplace(v1,v2): #最多接收两个参数,而且这个过滤器和其他过滤器一样,可以放到if判断for循环等语句里面来使用 # v1 = 'hello' # v2 = 'xxx' hellxxx return v1.replace('o',v2) @register.simple_tag def func1(v1,v2,v3): #自定义标签,可以接收任意多个参数,不可以放到if判断for循环等语句里面来使用
 s = v1 + v2 + v3 return s @register.inclusion_tag('result.html') 
def my_inc(n):
n=5
l1 = [i for i in range(n)]
return {'data':l1}

@register.simple_tag
def atag(v1): a = "<a href="">%s</a>"%v1
return mark_safe(a)

     (5) 使用自定义前(当然是在html文件中使用),使用时,先写:

     {% load mytag %}      

      然后

    python,view中

    

def test(request):

    return render(request,'test.html',{'name':'hello',})

  html中使用  

{{ name|myreplace:'xxx' }}

  

 整个流程:   自定义过滤器定义好后,依然是view中通过render传过来的参数,传到html文件中进行渲染,当然此处用的是过滤器,还是调用的自定义过滤器,name就是render传过来的hello, 通过"|"管道符调用过滤器函数(方法),将hello和"xxx"两个参数传到myreplace函数中,处理完返回结果.类似:name=myrepalce(name,'xxx')

  在html中,自定义过滤器是可以放在if判断和for循环的语句中的

{% if name|myreplace:'xxx'===hello %}
........
{% endif %}

二.   自定义标签:

  (1)自定义标签是不能应用到for循环与if判断语句里面的;传的参数不限个数.

  (2)在register.simple_tag装饰注册,

  (3) 引用:

<h1>
    {% func1 name age hobby %}
</h1>

  把name,age,hobby三个参数传到func1里,再将结果返回到页面显示.

(1)总结的好全: https://www.cnblogs.com/sss4/p/7071183.html

超哥:https://www.cnblogs.com/clschao/articles/10414811.html#part_4

    

猜你喜欢

转载自www.cnblogs.com/kevin-red-heart/p/10478120.html