編寫自訂的Django模板載入器的簡單樣本

來源:互聯網
上載者:User
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中。

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.