Jinja2 is one of the most used template engines for Python. It is inspired by Django's templating system but extends it with an expressive language that gives template authors a more powerful set of tools. On top of that it adds sandboxed execution and optional automatic escaping for applications where security is important.
Usually this is done inside a python virtualenv.
$ pip install jinja2
Every time though I have to spend some time figuring out how to lay out my files and how to load the template. So here is an example that you can also use as a skeleton for your next application.
.
├── run.py
├── html
│ └── index.html
└── templates
└── index.html
from jinja2 import Environment, FileSystemLoader
import os
root = os.path.dirname(os.path.abspath(__file__))
templates_dir = os.path.join(root, 'templates')
env = Environment( loader = FileSystemLoader(templates_dir) )
template = env.get_template('index.html')
filename = os.path.join(root, 'html', 'index.html')
with open(filename, 'w') as fh:
fh.write(template.render(
h1 = "Hello Jinja2",
show_one = True,
show_two = False,
names = ["Foo", "Bar", "Qux"],
))
<h1>{{ h1 }}</h1>
{% if show_one %}
<h2>one</h2>
{% endif %}
{% if show_two %}
<h2>two</h2>
{% endif %}
<ul>
{% for name in names %}
<li>{{ name }}</li>
{% endfor %}
</ul>
When run.py
is executed html/index.html
will have the following contents.
<h1>Hello Jinja2</h1>
<h2>one</h2>
<ul>
<li>Foo</li>
<li>Bar</li>
<li>Qux</li>
</ul>