• Django干货:自定义过滤器和标签


    一 文件路径配置

    自定义标签及过滤器也有自己的存放目录”templatetags"。

    (1)在项目目录中新建python package命名为common并在主目录settings.py中进行注册

    (2)在common下新建python package命名为“templatetags"

    (3)在templatetags中新建python文件命名为”common_custom"

    二、自定义过滤器

    方式一:装饰器注册

    (1)在新建好的common_custom文件中编写自定义函数

    1. #!/usr/bin/env python
    2. # -*- coding:utf-8 -*-
    3. __author__ = 'IT小叮当'
    4. __time__ = '2019-01-18 20:13'
    5. from django import template
    6. #创建注册器
    7. register = template.Library()
    8. #装饰器的方法注册自定义过滤器
    9. @register.filter
    10. #实现首字母变大写其余字母均小写的功能
    11. def my_lowercap(value):
    12. return value.capitalize()

     在建好的template中movie主页index模版中测试

    首先加载自定义过滤器文件,之后在使用自定义过滤器

    1. {% load common_custom %}
    2. <!DOCTYPE html>
    3. <html lang="en">
    4. <head>
    5. <meta charset="UTF-8">
    6. <title>movie主页</title>
    7. </head>
    8. <body>
    9. 我是原始的:{{ test }}<br><br>
    10. 我使用了内置lower过滤器:{{ test|lower }}<br><br>
    11. 我使用了内置capfirst过滤器:{{ test|capfirst }}<br><br>
    12. 我串联使用了lower过滤器和capfirst过滤器:{{test|lower|capfirst }}<br><br>
    13. 我使用了小叮当自定义的my_lowercap过滤器:{{ test|my_lowercap}}<br><br>
    14. </body>
    15. </html>

    浏览器中显示:

     

    可见,虽然内置的过滤器不能直接实现“首字母变大写,其余字母变小写。”但是,我们可以通过自定义过滤器的方法一步到位。

    值得注意的是,使用装饰器注册自定义过滤器时,还可通过在装饰器中传参的方式,重命名自定义的过滤器名字。

    1. #!/usr/bin/env python
    2. # -*- coding:utf-8 -*-
    3. __author__ = 'IT小叮当'
    4. __time__ = '2019-01-18 20:13'
    5. from django import template
    6. #创建注册器
    7. register = template.Library()
    8. #装饰器的方法注册自定义过滤器
    9. @register.filter('Mystyle')
    10. #实现首字母变大写其余字母均小写的功能
    11. def my_lowercap(value):
    12. return value.capitalize()

    此时在模版中使用过滤器my_lowercap便会报错

     

     使用重命名后的过滤器Mystyle

    代码如下

    我使用了小叮当自定义的my_lowercap过滤器:{{ test|Mystyle}}<br><br>

     在浏览器中查看

    方式二:函数调用的方式注册

    在common_custom中添加如下代码:

    1. #自定义实现cut过滤器功能
    2. def my_cut(value,arg):
    3. return value.replace(arg,'')
    4. #函数调用的方法注册自定义过滤器
    5. register.filter(my_cut)

    在模版中使用如下

    1. {% load common_custom %}
    2. <!DOCTYPE html>
    3. <html lang="en">
    4. <head>
    5. <meta charset="UTF-8">
    6. <title>movie主页</title>
    7. </head>
    8. <body>
    9. 我是原始的:{{ test }}<br><br>
    10. 我使用了内置cut过滤器过滤IS:{{ test|cut:'IS'}}<br><br>
    11. 我使用了小叮当自定义的cut过滤器过滤IS:{{ test|my_cut:'IS'}}<br><br>
    12. 我使用了内置cut过滤器过滤空格:{{ test|cut:'IS'}}<br><br>
    13. 我使用了小叮当自定义的cut过滤器过滤空格:{{ test|my_cut:'IS'}}<br><br>
    14. </body>
    15. </html>

    在浏览器中查看

    小结:

    自定义过滤器就是一个带有一个或两个参数的Python 函数:

    - (输入的)变量的值 —— 不一定是字符串形式。

    - 参数的值 —— 可以有一个初始值,或者完全不要这个参数

    三、自定义标签 

     

    自定义标签分为简单标签和包含标签。

    简单标签django.template.Library.simple_tag()

    包含标签django.template.Library.inclusion_tag()

    tag()方法有两个参数:

    (1) 模板标记的名称 - 字符串。 如果省略,将使用编译函数的名称。

    (2)编译的函数 – 一个Python函数(不要把函数名写成字符串)

    与过滤器注册一样,也可以将其用作装饰器。

    1.简单标签

    (1)在"common_custom.py"中自定义简单标签

    代码如下:

    1. #自定义简单标签输出当前时间
    2. import datetime
    3. @register.simple_tag
    4. def current_time():
    5. format_date = '%Y年%m月%d日 %H:%M:%S'
    6. return datetime.datetime.now().strftime(format_date)

    (2)在templates的movie下的index模版中进行测试

    1. {% load common_custom %}
    2. <!DOCTYPE html>
    3. <html lang="en">
    4. <head>
    5. <meta charset="UTF-8">
    6. <title>movie主页</title>
    7. </head>
    8. <body>
    9. 我是小叮当自定义的简单标签:{% current_time %}<br>
    10. </body>
    11. </html>

    浏览器中查看

    简单标签传参--模版中传参

    模版标签的传参格式:”标签名称+空格+参数“

    自定义可传参的简单标签

    1. @register.simple_tag
    2. def current_time2(format_date):
    3. return datetime.datetime.now().strftime(format_date)

    在模版中传参

    我还是小叮当自定义的简单标签,我从模版中传参:{% current_time2 '%Y年%m月%d日 %H:%M:%S' %}<br>

    到浏览器中查看

    简单标签传参--视图函数中通过”上下文“传参

    (1)在movie的views.py中的视图函数里通过"context"上下文传参

    1. def index(request,age):
    2. return render(request,'movie/index.html',
    3. context={'format_date':'%Y年%m月%d日 %H:%M:%S',
    4. }
    5. )

    (2)在"common_custom.py"中自定义简单标签

    1. @register.simple_tag(takes_context=True)
    2. def current_time3(context):
    3. format_date=context.get('format_date')
    4. return datetime.datetime.now().strftime(format_date)

    需要注意的是,通过视图函数上下文传参定义的简单标签,需要在简单标签装饰器中令”takes_context=True"(takes_context默认为False)

    (3)在模板中引用

    1. 1我是小叮当自定义的简单标签:{% current_time %}<br>
    2. 2我还是小叮当自定义的简单标签,我从模版中传参:{% current_time2 '%Y年%m月%d日 %H:%M:%S' %}<br>
    3. 3我也是小叮当自定义的简单标签,我通过视图函数context传参:{% current_time3 %}<br>

    (4)在浏览器中查看

    2.包含标签

    #1问题引入

    (1)movie主页视图函数

    1. #定义列表
    2. li=['a','b','c']
    3. #定义字典
    4. di={'x':1,'y':2}
    5. tup=('x','y','z')
    6. mytest="THIS IS TEST!"
    7. #导入时间模块
    8. import datetime
    9. def index(request,age):
    10. return render(request,'movie/index.html',
    11. context={'format_date':'%Y年%m月%d日 %H:%M:%S',
    12. 'strname':'我是字符串',#传递字符串
    13. 'hello':hello,#传递自定义函数
    14. 'xdd_say':xdd_info.say,#传递类方法
    15. 'xdd':xdd_info,#传递类对象
    16. 'list':li,#传递列表
    17. 'dict':di,#传递字典
    18. 'test':mytest,
    19. 'xdd666':None,
    20. 'num1':18,
    21. 'num2':2,
    22. 'html':'

      THIS IS IN HTML!

      '
      ,
    23. 'float':3.1415,
    24. 'now':datetime.datetime.now,
    25. 'tuple':tup,
    26. }
    27. )

    (2)movie主页模版

    1. {% load common_custom %}
    2. <!DOCTYPE html>
    3. <html lang="en">
    4. <head>
    5. <meta charset="UTF-8">
    6. <title>movie主页</title>
    7. </head>
    8. <body>
    9. {% for i in list %}
    10. <li>{{ i }}</li>
    11. {% endfor %}
    12. {% for i in tuple %}
    13. <li>{{ i }}</li>
    14. {% endfor %}
    15. </html>

    (3)浏览器中查看

    我们发现,要实现列表list变量和元组tuple变量的显示,for循环模版标签几乎一样,不同的只是传入的对象从list变成了tuple

    为了避免代码重复,我们可以使用包含标签的方法。

    (4)我们在templates下movie中新建“show_tags"html文件将,重复的代码复制到其中。

    代码如下:

    1. {% for i in choice %}
    2. <li>{{ i }}li>
    3. {% endfor %}

    #2自定义包含标签固定传参

    (1)在"common_custom.py"中自定义包含标签

    1. #自定义包含标签并与重复部分的代码绑定
    2. @register.inclusion_tag('movie/show_tags.html')
    3. def custom_for():
    4. test_list=['ax','ay','az']
    5. #将固定参数test_list传给自定义模版标签变量choice
    6. return {'choice':test_list}

    (2)在movie模版主页使用

    1. {% for i in list %}
    2. <li>{{ i }}</li>
    3. {% endfor %}
    4. {% for i in tuple %}
    5. <li>{{ i }}</li>
    6. {% endfor %}
    7. --------------------------------------<br>
    8. 我使用了小叮当自定义的包含标签custom_for
    9. {% custom_for %}

    (3)在浏览器中查看

    #3自定义包含标签 通过标签自己传参

    (1)在"common_custom.py"中自定义包含标签

    1. @register.inclusion_tag('movie/show_tags.html')
    2. def custom_for2(args):
    3. return {'choice':args}

    (2)在movie模版主页使用并传入参数list

    1. {% for i in list %}
    2. <li>{{ i }}</li>
    3. {% endfor %}
    4. {% for i in tuple %}
    5. <li>{{ i }}</li>
    6. {% endfor %}
    7. --------------------------------------<br>
    8. 我使用了小叮当自定义的包含标签custom_for
    9. {% custom_for %}
    10. --------------------------------------<br>
    11. 我使用了小叮当自定义的包含标签custom_for2
    12. {% custom_for2 list %}

    (3)在浏览器中查看

    #4自定义包含标签 接受上下文传参

    (1) 在"common_custom.py"中自定义包含标签

    1. @register.inclusion_tag('movie/show_tags.html',takes_context=True)
    2. def custom_for3(context):
    3. args=context.get('list')
    4. return {'choice':args}

    传入了对应视图函数中的list

    (2)在模版中使用自定义包含标签

    1. {% for i in list %}
    2. <li>{{ i }}</li>
    3. {% endfor %}
    4. {% for i in tuple %}
    5. <li>{{ i }}</li>
    6. {% endfor %}
    7. --------------------------------------<br>
    8. 我使用了小叮当自定义的包含标签custom_for
    9. {% custom_for %}
    10. --------------------------------------<br>
    11. 我使用了小叮当自定义的包含标签custom_for2
    12. {% custom_for2 list %}
    13. --------------------------------------<br>
    14. 我使用了小叮当自定义的包含标签custom_for3
    15. {% custom_for3 %}

    (3)在浏览器中查看

  • 相关阅读:
    Python离线断网情况下安装numpy、cv2和matplotlib等常用第三方包
    国产1.8V低电压输入,可用于驱动步进电机;H 桥驱动电路单元可以直接驱动IR-CUT
    leetcode二叉树系列(二)
    springboot项目实现helloworld
    【Android面试八股文】讲一讲StackOverFlow和OOM的区别?栈和堆分别存储的是什么?
    Spire.XLS for Java 12.11.8 Excel to PDF bug Fix
    【rbac简介】
    Javascriput中数组的创建以及最值的求法
    springboot+vue网上学生评教系统java
    STM32实战总结:HAL之电机
  • 原文地址:https://blog.csdn.net/hsabrina/article/details/127714287