创建项目
django-admin startapp the_6
过滤器定义与使用
新建过滤器文件——创建过滤器项目
from django import template
register = template.Library()
# 过滤器
@register.filter()
# low : 把视图函数的返回对象改成小写
def low(value):
return value.lower()
from django.http import HttpResponse
from django.shortcuts import render
# Create your views here.
def filter_custom(request):
return render(request,'the_6/filter_custom.html',{'XX': 'HELLO WORD'})
{#申明#}
{% load loa %}
HELLO filter_custom的文件 <br>
{#渲染#}
{{ XX }}
{#加过滤器#}
{{ XX|low }}
加了过滤器之后——把视图函数的返回对象变成小写
带参过滤器
from django.http import HttpResponse
from django.shortcuts import render
# Create your views here.
def the_6_hello(request):
return HttpResponse('hello')
def filter_custom(request):
return render(request,
'the_6/filter_custom.html',
{'XX': 'HELLO WORD',
'yy': '我是真实值',
})
# 带参过滤器
@register.filter
def default(value, parm):
return value or parm
{#带参过滤器——传值就用,不传就用默认值#}
{{ yy | default:'我是默认值' }}
自定义标签
simple_tag
# 自定义标签
@register.simple_tag()
def teg(a1,a2,a3):
return '{}_{}_{}'.format(a1,a2,a3)
def filter_custom(request):
return render(request,
'the_6/filter_custom.html',
{'XX': 'HELLO WORD',
'yy': '我是真实值',
'p1': 'I',
'p2': 'Love',
'p3': 'you'
})
{#自定义标签#}
{% teg p1 p2 p3 %}
inclusion_tag ——可以把 a 页面渲染到 b 页面
# inclusion_tag
@register.inclusion_tag('the_6/inclusion.html')
def incl_tag():
return {'lan': 'python'}
<h2>
我能拿到 lan 里面的 {{ lan }}
</h2>
页面 b
{#申明#}
{% load loa %}
HELLO filter_custom的文件 <br>
{#渲染#}
{{ XX | low }} <br>
{#带参过滤器——传值就用,不传就用默认值#}
{{ yy | default:'我是默认值' }} <br>
{#自定义标签#}
{% teg p1 p2 p3 %}
{# 渲染页面 a #}
{% incl_tag %}