第一,決定模板庫應該放在哪一個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)