Python 中是否有纯文本文件的本机模板系统?

我正在为 Python 寻找将输出格式化为简单文本的技术或模板系统。我需要的是它能够遍历多个列表或字典。如果我能够将模板定义为单独的文件(如 output.templ) ,而不是将其硬编码为源代码,那就太好了。

作为一个简单的例子,我想实现的,我们有变量 titlesubtitlelist

title = 'foo'
subtitle = 'bar'
list = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']

通过模板运行,输出如下:

Foo
Bar


Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday

怎么做? 谢谢。

102337 次浏览

There are quite a number of template engines for python: Jinja, Cheetah, Genshi etc. You won't make a mistake with any of them.

If your prefer to use something shipped with the standard library, take a look at the format string syntax. By default it is not able to format lists like in your output example, but you can handle this with a custom Formatter which overrides the convert_field method.

Supposed your custom formatter cf uses the conversion code l to format lists, this should produce your given example output:

cf.format("{title}\n{subtitle}\n\n{list!l}", title=title, subtitle=sibtitle, list=list)

Alternatively you could preformat your list using "\n".join(list) and then pass this to your normal template string.

I don't know if it is simple, but Cheetah might be of help.

You can use the standard library string an its Template class.

Having a file foo.txt:

$title
$subtitle
$list

And the processing of the file (example.py):

from string import Template


d = {
'title': 'This is the title',
'subtitle': 'And this is the subtitle',
'list': '\n'.join(['first', 'second', 'third'])
}


with open('foo.txt', 'r') as f:
src = Template(f.read())
result = src.substitute(d)
print(result)

Then run it:

$ python example.py
This is the title
And this is the subtitle
first
second
third