2010-12-10 99 views

回答

11

對於一個非常小的模板任務,Python本身並沒有那麼糟糕。例如:

def dynamic_text(name, food): 
    return """ 
    Dear %(name)s, 
    We're glad to hear that you like %(food)s and we'll be sending you some more soon. 
    """ % {'name':name, 'food':food} 

從這個意義上講,您可以在Python中使用字符串格式來進行簡單的模板化。這就像它的輕量級一樣。

如果你想深入一點,Jinja2是許多人認爲最「設計友好」(閱讀:簡單)的模板引擎。

你也可以看看Mako和Genshi。最終,選擇是你的(有什麼你想要的功能,並與你的系統很好地集成)。

+1

我同意,很多時候Python的格式化工具正是需要的。你可以做一些像`「Hello {foo}」格式(foo =「World」)`。也可以考慮Python'string`模塊:http://docs.python.org/library/string.html#template-strings 但是,一旦你開始需要一些條件或迭代邏輯in-template,你需要一些東西正如其他答案中所建議的那樣。 – 2010-12-10 06:07:54

12

有什麼不對嗎string.Template?這是標準的Python分配和PEP 292覆蓋:

from string import Template 

form=Template('''Dear $john, 

I am sorry to imform you, $john, but you will not be my husband 
when you return from the $theater war. So sorry about that. Your 
$action has caused me to reconsider. 

Yours [NOT!!] forever, 

Becky 

''') 

first={'john':'Joe','theater':'Afgan','action':'love'} 
second={'john':'Robert','theater':'Iraq','action':'kiss'} 
third={'john':'Jose','theater':'Korean','action':'discussion'} 

print form.substitute(first) 
print form.substitute(second) 
print form.substitute(third) 
+1

str.format()比string.Template功能強大得多,但卻非常簡單。 – Apalala 2013-02-28 14:37:14

0

搜索在谷歌微小的模板的Python止跌回升Titen,其源代碼是唯一5.5 kB。 Titen可以對列表進行迭代,其中內置str.format不能。

Mako聲稱重量輕,但與Titen相比,它相對較胖(> 200kB)。 Jinja2和Django模板也大大超過100 kB。

-2

試用一下蟒蛇微模板:

https://github.com/diyism/python-micro-template

使用實例(kivy):

import python_micro_template 
... 
kvml=open('example_kivy_scrollview.kvml', 'r').read() 
kvml=python_micro_template.tpl.parse(kvml) 
grid=Builder.load_string(kvml) 
... 

模板實例(kvml):

<:for i in range(30):#{#:> 
Button: 
    text: '<:=i:><:for j in range(6):#{#:><:=j:><:#}#:>' 
    size: 480, 40 
    size_hint: None, None 
<:#}#:>