【发布时间】:2010-12-10 05:53:00
【问题描述】:
这是 Python 中最简单、轻量级的 html 模板引擎,我可以使用它来生成自定义的电子邮件通讯。
【问题讨论】:
标签: python templating
这是 Python 中最简单、轻量级的 html 模板引擎,我可以使用它来生成自定义的电子邮件通讯。
【问题讨论】:
标签: python templating
对于一个非常小的模板任务,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。最终,选择权在您手中(具有您喜欢的功能并与您的系统完美集成的功能)。
【讨论】:
"Hello {foo}".format(foo="World") 之类的操作。还要考虑一下,Python string 模块:docs.python.org/library/string.html#template-strings 但是一旦您开始在模板中需要一些条件或迭代逻辑,您将需要其他答案中建议的更实质性的东西。
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)
【讨论】:
我认为Werkzeug Mini Templates 非常适合。
这是 Github 上的 the source code。
【讨论】:
试试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
<:#}#:>
【讨论】: