python中的模板系統比較多,我比較喜歡用的是mako。
mako模板的功能
變量取代:
${}
在里面可以執行python內建的函數,以及通過模板Context傳遞過來的變量取代,受jsp等影響。
過濾器(文檔說是 Expression Escaping-表達式轉義)
在變量取代中 | 來表示過濾,內建 u-URL escaping, h-HTML escaping, x-XML escaping,以及trim四個過濾器。
結構控制
有if/else/elif, while/for, try/except,用%開頭,用%end<name>結尾,name為表達式名稱,與python一樣,需要尾部添加:來表示一個表達式開始,但縮進不是必須的。
由於%被特殊使用,所有想要表達%,得用%%
注釋
和其他語言一樣,有單行和多行注釋,單行用##,多行用<%doc></%doc>
換行過濾器
\在一行的結尾,表示下一行也是這一行的內容,連接上下兩行內容為一行內容。
here is a line that goes onto \ another line.
等價:
here is a line that goes onto another line.
Python塊
mako支持python代碼塊,用<%開始,用%>結束
this is a template <% x = db.get_resource('foo') y = [z.element for z in x if x.frobnizzle==5] %> % for elem in y: element: ${elem} % endfor
上面的一個變形是模塊級別的支持,用<%!開始
<%! import mylib import re def filter(text): return re.sub(r'^@', '', text) %>
注意,此處需要純的python代碼
標簽
類似XML,用%開頭,用/結束或者顯示的結束標簽
<%include file="foo.txt" />
<%def name="foo" buffered="True">
this is a def
</%def>
所有的tag有各自的屬性,大部分屬性支持evaluation,這表示你可以在屬性文本中使用${}
<%include file="/foo/bar/${myfile}.txt" />
下面為所有tag
<%page>
每個模板中僅能使用一個<%page>標簽,剩下的會被忽略。
<%include>
包含一個文件,然后將文件render出來,include可以包含參數
<%include file="toolbar.html" args="current_section='members', username='ed" />
<%def>
定義一個python函數,可以被其他的模板調用
<%def name="myfunc(x)">
this is myfunc, x is ${x}
</%def>
<%block>
類似%def,可以匿名,從Jinja2中的block中引用過來
<%namespace>
等價於python的import語句,可以用來render函數以及模板文件源數據,python模塊等。
<%inherit>
允許模板構成繼承鏈,當構成inherit時,控制首先運行inherit部分模板。
<%nsname:defname>
任何用戶定義的名字,類似於<%call>的行內調用
<%call>
比上面的<%nsname:defname>要復雜
<%doc>
多行注釋
<%text>
掛起mako語法分析,返回整個文本,通常用來編寫文檔時使用
從模板中快速返回
有時候想要停止處理模板或者<%def>,在python的block中使用return語句。
%if not len(records):
no records found.
<% return %>
%endif
或
<%
if not len(records):
return
%>
