這篇文章主要介紹了編寫自定義的Django模板加載器的簡單示例,Django是各色人氣Python框架中最為著名的一個,需要的朋友可以參考下
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 settings
- 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."
- 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中。
新聞熱點
疑難解答