轻量级Python模板引擎

10 投票
4 回答
13852 浏览
提问于 2025-04-16 08:20

在Python中,哪个是最简单、最轻量的HTML模板引擎,我可以用来生成定制的电子邮件通讯?

4 个回答

0

在谷歌上搜索tiny template Python时,找到了Titen,它的源代码只有5.5 kB。Titen可以对列表进行循环,而内置的str.format做不到这一点。

Mako自称是轻量级的,但和Titen比起来,它的体积相对较大(超过200 kB)。Jinja2和Django模板的大小也都超过了100 kB。

21

关于 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)
19

对于一些非常简单的模板任务,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。最终,选择权在你手里(看哪个有你想要的功能,并且能和你的系统很好地结合)。

撰写回答