Djangos 內建的模板載入器(在先前的模板載入內幕章節有敘述)通常會滿足你的所有的模板載入需求,但是如果你有特殊的載入需求的話,編寫自己的模板載入器也會相當簡單。 比如:你可以從資料庫中,或者利用Python的綁定直接從Subversion庫中,更或者從一個ZIP文檔中載入模板。
模板載入器,也就是 TEMPLATE_LOADERS 中的每一項,都要能被下面這個介面調用:
load_template_source(template_name, template_dirs=None)
參數 template_name 是所載入模板的名稱 (和傳遞給 loader.get_template() 或者 loader.select_template() 一樣), 而 template_dirs 是一個可選的代替TEMPLATE_DIRS的搜尋目錄列表。
如果載入器能夠成功載入一個模板, 它應當返回一個元組: (template_source, template_path) 。在這裡的 template_source 就是將被模板引擎編譯的的模板字串,而 template_path 是被載入的模板的路徑。 由於那個路徑可能會出於調試目的顯示給使用者,因此它應當很快的指明模板從哪裡載入。
如果載入器載入模板失敗,那麼就會觸發 django.template.TemplateDoesNotExist 異常。
每個載入函數都應該有一個名為 is_usable 的函數屬性。 這個屬性是一個布爾值,用於告知模板引擎這個載入器是否在當前安裝的Python中可用。 例如,如果 pkg_resources 模組沒有安裝的話,eggs載入器(它能夠從python eggs中載入模板)就應該把 is_usable 設為 False ,因為必須通過 pkg_resources 才能從eggs中讀取資料。
一個例子可以清晰地闡明一切。 這兒是一個模板載入函數,它可以從ZIP檔案中載入模板。 它使用了自訂的設定 TEMPLATE_ZIP_FILES 來取代了 TEMPLATE_DIRS 用作尋找路徑,並且它假設在此路徑上的每一個檔案都是包含模板的ZIP檔案:
from django.conf import settingsfrom django.template import TemplateDoesNotExistimport zipfiledef load_template_source(template_name, template_dirs=None): "Template loader that loads templates from a ZIP file." 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() # We found a template, so return the source. template_path = "%s:%s" % (fname, template_name) return (source, template_path) # If we reach here, the template couldn't be loaded raise TemplateDoesNotExist(template_name)# This loader is always usable (since zipfile is included with Python)load_template_source.is_usable = True
我們要想使用它,還差最後一步,就是把它加入到 TEMPLATE_LOADERS 。 如果我們將這個代碼放入一個叫mysite.zip_loader的包中,那麼我們要把mysite.zip_loader.load_template_source加到TEMPLATE_LOADERS中。