2010年8月21日 星期六

自訂範本系統中的 filter

在 App Engine 上製作網頁時,若是沒有使用 django 或是其它的 template 函式庫,應該都會直接使用 App Engine 所提供的 django template wrapper(用的是 django 0.96 版的 template),不過這就沒辦法(很簡單地)照著 django 所提供的方式自訂標籤及 filter。不過 App Engine 還是有提供自訂 filter 的方式,只要按照下列的步驟(假設你應用程式的目錄是在 $APP):
  1. 建立一個 Python 模組來定義 filters:
    # $APP/my_filters.py
    from google.appengine.ext import webapp
    
    # 取得 template filters register
    register = webapp.template.create_template_register()
    
    @register.filter
    def tolower(string_value):
        return string_value.lower()
    
    這樣一來便建立了一個自訂的 filter: tolower,等等便可以用在 template 中。
  2. 雖然建立好了自訂的 filter(s),但是 App Engine 的 template 函式庫還不知道有這個東西的存在,所以在使用範本引擎輸出前,記得加入下列的程式碼註冊你自訂的 module(s):
    ...
    from google.appengine.ext.webapp import template
    
    # 註冊自訂 filters 的模組(載入模組的名稱)
    template.register_template_library('my_filters')
    
  3. 完成以上步驟後,就可以在範本中像這樣來使用自訂的 filters:
    ...
    Description: {{ description|tolower }}
    

如此一來,便不必在 request handler 中預先處理輸出的內容,可以把這部份的程式碼用 filter 來解決。

沒有留言:

張貼留言