假设有模版变量{{ name }}会被rendering,但是想显示小写的英文,那么可以这样:
{{ name|lower }}
“|”后面的lower就是过滤器--系统自带的过滤器
我们可以自己定义过滤器,并注册进来像自带过滤器一样使用:
创建一个模版库
这里我单独为模版库建了一个应用(推荐),这样,模版库中的过滤器(filter)可能在其他应用中也可以使用
应用名字templateLibrary,
注意:
1.里面要有__init__.py
2.该应用要在setting.py中注册
3.使用时要先
{% load app_extras %}
mysite
mysite\
__init__.py
setting.py
urls.py
views.py
wsgi.py
static\
css\
bootstrap.css
js\
bootstrap.js
templates\
base.html
cloud.html
templateLibrary\
__init__.py
views.py
templatetags\
__init__.py
app_extras.py
manage.py
其中的app_extras.py就是自定义的过滤器:
from django import template
register = template.Library()
#一个模块级变量,是必须的
@regoster.filter(name = 'cut')
#注册成为合法的过滤器
def cut(value, arg):
"Removes all values of arg from the given string"
return value.replace(arg, '')
下面是一个应用的例子:
{{ somevariable|cut:" " }}
作用是去掉变量值中的空格
附:两种加载模版的方法
django.template.loader.get_template(template_name)
django.template.loader.select_template(template_name_list)
第一个会根据给定的模版名称返回一个已编译的模版(一个Template对象),模版不存在,触发:TemplateDoesNotExist异常;
第二个不同的是以模版名称列表为参数,它会返回列表中存在的第一个模版,如果模版都不存在,触发:TemplateDoesNotExist异常。