第一,决定模板库应该放在哪个Django应用下。 如果你通过 manage.py startapp 创建了一个应用,你可以把它放在那里,或者你可以为模板库单独创建一个应用。 我们更推荐使用后者,因为你的filter可能在后来的工程中有用。
第二,在适当的Django应用包里创建一个 templatetags 目录。 这个目录应当和 models.py 、 views.py 等处于同一层次。 例如:
books/ __init__.py models.py templatetags/ views.py
在 templatetags 中创建2个文件, 一个 __init__.py 另一个用来存放自定义标签和过滤器的文件,此文件的名字将用来在模板中加载标签,如文件名叫 poll_extras.py 模板中就需写入
{% load poll_extras %}
from django import template #导入模板包 register = template.Library() #register 的模块级变量,template.Library的实例 @register.filter(name='cut') # 注册过滤器 name: 过滤器名称,缺省时为函数名(eg: cut) def cut(value, arg): return value.replace(arg, '')
@register.tag #注册标签 def num_plus(parser, token): try: v1, v2 = token.split_contents() sum = int(v1) + int(v2) except ValueError: msg = 'please enter a number' raise template.TemplateSyntaxError(msg) return NumPlusNode(sum) class NumPlusNode(template.Node): def __init__(self, sum): self.sum = sum def render(self, context): return self.sum
Django提供了一个帮助函数simple_tag。这个函数是django.template.Library的一个方法,它接受一个只有一个参数的函数作参数,把它包装在render函数和之前提及过的其他的必要单位中,然后通过模板系统注册标签。
@register.simple_tag def current_time(format_string): try: return datetime.datetime.now().strftime(str(format_string)) except UnicodeEncodeError: return ''
{% books_for_author author %}
结果:
<ul> <li>The Cat In The Hat</li> <li>Hop On Pop</li> <li>Green Eggs And Ham</li> </ul>模板片段
def books_for_author(author): books = Book.objects.filter(authors__id=author.id) return {'books': books}创建用于渲染标签输出的模板
<ul> {% for book in books %} <li>{{ book.title }}</li> {% endfor %} </ul>通过对一个 Library 对象使用 inclusion_tag() 方法来创建并注册这个包含标签。
if the preceding template is in a file called book_snippet.html, we register the tag like this:
@register.inclusion_tag('book_snippet.html') def books_for_author(author): # ...模板加载器,也就是 TEMPLATE_LOADERS 中的每一项,都要能被下面这个接口调用:
load_template_source(template_name, template_dirs=None)