Videos
ยป pip install templates
Anything wrong with string.Template? This is in the standard Python distribution and covered by 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)
For a really minor templating task, Python itself isn't that bad. Example:
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}
In this sense, you can use string formatting in Python for simple templating. That's about as lightweight as it gets.
If you want to go a bit deeper, Jinja2 is the most "designer friendly" (read: simple) templating engine in the opinion of many.
You can also look into Mako and Genshi. Ultimately, the choice is yours (what has the features you'd like and integrates nicely with your system).
Best suggestion: try them all. It won't take long.
My favourite: Jinja2 (by a mile)
It has decent syntax, can trace errors through it, and is sandboxable.
If you're doing code generation, you might find Cog useful - it's specifically for code generation, rather than being a generally applicable templating language.
You can use the standard library string and its Template class.
Given an input file foo.txt:
$title
$subtitle
$list
And this code in 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
There are quite a number of template engines for python: Jinja, Cheetah, Genshi etc. You won't make a mistake with any of them.