Mako是一個高性能的Python模板庫,它的語法和API借鑒了很多其他的模板庫,如Django、Jinja2等等。
基本用法
創建模板并渲染它的最基本的方法是使用 Template 類:
from mako.template import Templatet = Template('hello world!')print t.render()
傳給 Template 的文本參數被編譯為一個Python模塊。模塊包含一個 render_body() 函數,它產生模板的輸出。調用 render() 方法時,Mako建立了一個模板的運行環境,并調用 render_body() 函數,把輸出保存到緩沖,返回它的字符串內容。
render_body() 函數中可以訪問一個變量集。可以向 render() 方法發送額外的關鍵詞參數來指定這些變量:
from mako.template import Templatet = Template('hello, ${name}!')print t.render(name='yeolar')
render() 方法使Mako創建一個 Context 對象,它存儲模板可以訪問的所有變量和一個用來保存輸出的緩沖。也可以自己創建 Context ,用 render_context() 方法使模板用它來渲染:
from mako.template import Templatefrom mako.runtime import Contextfrom StringIO import StringIOt = Template('hello, ${name}!')buf = StringIO()c = Context(buf, name='yeolar')t.render_context(c)print buf.getValue()
使用文件模板
Template 也可以從文件加載模板,使用 filename 參數:
from mako.template import Templatet = Template(filename='/docs/tpl.txt')print t.render()
為了提高性能,從文件加載的 Template 還可以在文件系統中將生成的模塊緩存為一般的Python模塊文件(.py文件),這通過添加 module_directory 參數實現:
from mako.template import Templatet = Template(filename='/docs/tpl.txt', module_directory='/tmp/mako_modules')print t.render()
上面的代碼渲染后,會創建一個/tmp/mako_modules/docs/tpl.txt.py文件,其中包含模塊的源代碼。下次同樣參數的 Template 創建時,自動重用這個模塊文件。
使用TemplateLookup
到現在的例子都是有關單個 Template 對象的用法。如果模板中的代碼要定位其他模板資源,需要某種使用URI來找到它們的方法。這種需求是由 TemplateLookup 類來達到的。這個類通過傳入一個模板查找目錄的列表來構造,然后作為關鍵詞參數傳給 Template 對象:
from mako.template import Templatefrom mako.lookup import TemplateLookuplookup = TemplateLookup(directories=['/docs'])t = Template('<%include file="header.txt" /> hello word!', lookup=lookup)
上面創建的模板中包含文件header.txt。為了查找header.txt,傳了一個 TemplateLookup 對象給它。
通常,應用會以文本文件形式在文件系統上存儲大部分或全部的模板。一個真正的應用會直接從 TemplateLookup 取得它的模板,使用 get_template() 方法,它接受需要的模板的URI作為參數:
新聞熱點
疑難解答