django1.5 自定义过滤器和标签

建立模板库:

第一,决定模板库应该放在哪一个Django应用下。 若是你经过 manage.py startapp 建立了一个应用,你能够把它放在那里,或者你能够为模板库单首创建一个应用。 咱们更推荐使用后者,由于你的filter可能在后来的工程中有用。 html

第二,在适当的Django应用包里建立一个 templatetags 目录。 这个目录应当和 models.py 、 views.py 等处于同一层次。 例如: python

books/
    __init__.py
    models.py
    templatetags/
    views.py

在 templatetags 中建立2个文件, 一个 __init__.py    另外一个用来存放自定义标签和过滤器的文件,此文件的名字将用来在模板中加载标签,如文件名叫 poll_extras.py  模板中就需写入 django

{% 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函数和以前说起过的其余的必要单位中,而后经过模板系统注册标签。 app

@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: this

@register.inclusion_tag('book_snippet.html')
def books_for_author(author):
    # ...
模板加载器,也就是 TEMPLATE_LOADERS  中的每一项,都要能被下面这个接口调用:

load_template_source(template_name, template_dirs=None)
相关文章
相关标签/搜索