Python 3home |
Jinja2 is a module for inserting data into templates.
As you know, features such as f'' strings and the .format() method are designed to insert "dynamic" data (that is, variables that may be any value) into "static" templates (text that does not change). This demonstrated the concept of templating. Jinja2 offers a full-featured templating system, including the following features:
Here is a basic example showing these features:
test.html, stored the test_templates/ directory
Hello, {{ name }}. Please say it loudly: {{ compliment.upper() }}! Must I tell you: {% for item in pronouncements %} {{ item }} {% endfor %} Or {{ pronouncements[0] }}? {% if not reconciled: %} We have work left to do. {% else %} I'm glad we worked that out. {% endif %}
test.py, in the same dir as test_templates
import jinja2
env = jinja2.Environment()
env.loader = jinja2.FileSystemLoader('test_templates')
template = env.get_template('test.html')
print(template.render(name='Joe', compliment="you're great",
pronouncements=['over', 'over', 'over again'],
reconciled=False))
The rendered template!
Hello, Joe. Please say it loudly: YOU'RE GREAT! Must I tell you: over over and over again Or over? We have work left to do.