李典的博客

导航

django自定义simple_tag和filter

1、在django的setting文件中,加入你创建的app,以app01为例

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'app01',
]

2、在django你的项目app01目录下,新建一个名为templatetags的模块:

  app01/

    -migrations

    -templatetags

    -admin.py

    ...

3、在templatetags模块下新增.py文件,例my_tag.py

  

  app01/

    -migrations

    -templatetags

      -my_tag.py

    -admin.py

    ...

4、在my_tag.py中,此中的register不可换成别的变量名,换了就报错:

from django import template

register = template.Library()

@register.simple_tag
def my_tag(a,b):
return a+b

@register.filter
def my_filter(a,b):
return a+b

5、在templates目录下新建html文件,在html头部加载你定义的simple_tag和my_filter,然后在body中加入你在my_tag.py文件中注册的simple_tag方法名:

{% load my_tag %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
{% my_tag %}
</body>
</html>

 6、对多个参数的simple_tag,在my_tag.py中的my_tag方法里加入参数,参数个数可以任意,根据实际需要来,如下: 

from django import template

register = template.Library()

@register.simple_tag
def my_tag(a,b):
return a+b

@register.filter
def my_filter(a,b):
return a+b

 7、然后在html文件中,把参数写在后边,my_filter过程类似,只是参数的位置和写法不一样如下:

{% load my_tag %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
{% my_tag 1 2 %}
   {{ 'hello' | my_filter:'world' }}
</body>
</html>

8、接下来说一说两个的区别:
  simple_tag
    -参数任意,但是不能作为if条件判断的条件
  filter
    -参数最多只能有两个,但是可以作为if条件判断的条件。



posted on 2018-03-28 09:41  python_李典  阅读(175)  评论(0编辑  收藏  举报