实现自定义过滤器
1. 创建register变量
register = template.Library()
2. 定义过滤器函数
#移除字符串中var的arg字串
return var.replace(arg, '')
"Converts a string into all lowercase"
return value.lower()
3. 注册过滤器函数
#第二个就是你的过滤器函数引用名
register.filter('remove', remove)
register.filter('lower', lower)
def remove(value, arg):
return value.replace(arg, '')
@register.filter
def lower(value):
return value.lower()
register = template.Library()
@register.filter(name='remove')
def remove(value, arg):
return value.replace(arg, '')
@register.filter
def lower(value):
return value.lower()
实现自定义tag
了解模板编译过程
{% ifequal name.birthday today %}
Happy birthday!
{% else %}
Be sure to come back on your birthday
for a splendid surprise message.
{% endifequal %}
- Text node: "Hello, "
- Variable node: person.name
- Text node: ".\n\n"
- IfEqual node: name.birthday and today
创建tag实战
1. 定义Node节点类,实现render方法
from django import template
#这一句还是要的
register = template.Library()
class CurrentTimeNode(template.Node):
def __init__(self, format_string):
self.format_string = str(format_string)
def render(self, context):
now = datetime.datetime.now()
#返回的是格式化后的时间表示字符串
return now.strftime(self.format_string)
2. 创建Compilation函数
try:
tag_name, format_string = token.split_contents()
except ValueError:
msg = '%r tag requires a single argument' % token.split_contents()[0]
raise template.TemplateSyntaxError(msg)
return CurrentTimeNode(format_string[1:-1])
每一个tag的编译函数都需要两个参数parser和token:
3. 注册tag
def do_current_time(parser, token):
# ...
@register.tag
def shout(parser, token):
# ...
不用名字,表示默认使用函数名
import datetime
register = template.Library()
@register.filter(name='remove')
def remove(value, arg):
return value.replace(arg, '')
@register.filter
def lower(value):
return value.lower()
class CurrentTimeNode(template.Node):
def __init__(self, format_string):
self.format_string = str(format_string)
def render(self, context):
now = datetime.datetime.now()
return now.strftime(self.format_string)
def do_current_time(parser, token):
try:
tag_name, format_string = token.split_contents()
except ValueError:
msg = '%r tag requires a single argument' % token.split_contents()[0]
raise template.TemplateSyntaxError(msg)
return CurrentTimeNode(format_string[1:-1])
register.tag('current_time', do_current_time)
4. 运行
复杂的实现自定义tag的其他几种方法
1. 在Node类的render函数中设置context
now = datetime.datetime.now()
#设置context对象的值
context['current_time'] = now.strftime(self.format_string)
# render函数一定要返回字符串,即使是空串
return ''
<<SPAN style="COLOR: #0000ff">p>The time is {{ current_time }}.</<SPAN style="COLOR: #0000ff">p>
<<SPAN style="COLOR: #0000ff">p>The current time is {{ my_current_time }}.</<SPAN style="COLOR: #0000ff">p>
class CurrentTimeNode3(template.Node):
def __init__(self, format_string, var_name):
#增加自定义变量名的参数
self.format_string = str(format_string)
self.var_name = var_name
def render(self, context):
now = datetime.datetime.now()
context[self.var_name] = now.strftime(self.format_string)
return ''
def do_current_time(parser, token):
#使用正规表达式来处理token
try:
# 使用string.split(sep[, maxsplit]),1代表最大分割数,也就是
# 分割后会产生maxsplit+1个元素
# 这里分割后的结果为(get_current_time, '"%Y-%M-%d %I:%M %p" as my_current_time')
tag_name, arg = token.contents.split(None, 1)
except ValueError:
msg = '%r tag requires arguments' % token.contents.split_contents()[0]
raise template.TemplateSyntaxError(msg)
#使用()代表正则组,匹配as两边的字符串
m = re.search(r'(.*?) as (\w+)', arg)
if m:
fmt, var_name = m.groups()
else:
msg = '%r tag had invalid arguments' % tag_name
raise template.TemplateSyntaxError(msg)
#如果格式没被引号引用,报错
if not (fmt[0] == fmt[-1] and fmt[0] in ('"', "'")):
msg = "%r tag's argument should be in quotes" % tag_name
raise template.TemplateSyntaxError(msg)
# [1:-1]去除格式两边的引号
return CurrentTimeNode3(fmt[1:-1], var_name)
register.tag('get_current_time', do_current_time)
2. 实现块作用区域的tag
nodelist = parser.parse(('endcomment',))
parser.delete_first_token()
return CommentNode()
class CommentNode(template.Node):
def render(self, context):
return ''
3. 在块作用tag中保留context内容
This will appear in uppercase, {{ user_name }}.
{% endupper %}
nodelist = parser.parse(('endupper',))
parser.delete_first_token()
return UpperNode(nodelist)
class UpperNode(template.Node):
def __init__(self, nodelist):
self.nodelist = nodelist
def render(self, context):
output = self.nodelist.render(context)
return output.upper()
4. 快速创建简单tag的方法
try:
return datetime.datetime.now().strftime(str(format_string))
except UnicodeEncodeError:
return ''
register.simple_tag(current_time)
def current_time(token):
# ...
5. 创建Inclusion Tag
<<SPAN style="COLOR: #0000ff">li>The Cat In The Hat</<SPAN style="COLOR: #0000ff">li>
<<SPAN style="COLOR: #0000ff">li>Hop On Pop</<SPAN style="COLOR: #0000ff">li>
<<SPAN style="COLOR: #0000ff">li>Green Eggs And Ham</<SPAN style="COLOR: #0000ff">li>
</<SPAN style="COLOR: #0000ff">ul>
- 定义函数
books = Book.objects.filter(authors__id=author.id)
return {'books': books}
- 创建另一个模板文件book_snippet.html
{% for book in books %}
<<SPAN style="COLOR: #0000ff">li>{{ book.title }}</<SPAN style="COLOR: #0000ff">li>
{% endfor %}
</<SPAN style="COLOR: #0000ff">ul>
- 注册tag
def jump_link(context):
return {
'link': context['home_link'],
'title': context['home_title'],
}
模板文件link.html为
创建自定义模板加载类
from django.template import TemplateDoesNotExist
import zipfile
def load_template_source(template_name, template_dirs=None):
"Template loader that loads templates from a ZIP file."
#从settings.py配置文件中读取属性TEMPLATE_ZIP_FILES的值,默认返回空列表
template_zipfiles = getattr(settings, "TEMPLATE_ZIP_FILES", [])
# Try each ZIP file in TEMPLATE_ZIP_FILES.
for fname in template_zipfiles:
try:
z = zipfile.ZipFile(fname)
source = z.read(template_name)
except (IOError, KeyError):
continue
z.close()
# 找到一个可用的文件就返回
template_path = "%s:%s" % (fname, template_name)
return (source, template_path)
# 如果一个zip文件没找到,报错
raise TemplateDoesNotExist(template_name)
# 设置为可用
load_template_source.is_usable = True
'books.zip_loader.load_template_source',
)