python的轻量级模板引擎

时间:2010-12-10 05:53:00

标签: python templating

这是Python中最简单,重量最轻的html模板引擎,可用于生成自定义的电子邮件简报。

5 个答案:

答案 0 :(得分: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 :(得分: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。最终,您可以选择(具有您喜欢的功能并与您的系统完美集成)。

答案 2 :(得分:1)

我认为Werkzeug Mini Templates非常适合该法案。

这是Github上的the source code

答案 3 :(得分:0)

在Google中搜索 tiny template Python ,发现了Titen,其源代码仅为5.5 kB。 Titen可以对列表进行迭代,内置的 str.format 不能。

Mako声称是轻量级的,但与Titen相比,它相对较胖(> 200 kB)。 Jinja2和Django模板也超过100 kB。

答案 4 :(得分:-2)

试试python-micro-template:

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
<:#}#:>
相关问题