Table of contents
jinja
install jinja
pip install -U Jinja2 # python2
pip3 install -U Jinja2 # python3
jinja hello world
#!/usr/bin/python3
import jinja2
template = jinja2.Template('Hello {{ name }}!')
print(template.render(name='John Doe'))
read template from file
template = jinja2.Template(open('template.html', 'r').read())
providing data as a dictionary
data = { "name": "me" }
print(template.render(data))
template syntax
comments
{# .. #}
using variables
{{ user.url }}
setting a variable
{% set a_string = 'example' %}
{% set a_reference = a_string %}
passing in a custom function
data["foo"] = lambda x: 'hello ' + x
{{foo('world')}}
ternary operator
{{ 'flag set' if flag else 'flag not set' }}
if else
{% if myvar is defined %}
{{myvar}}
{% else %}
undefined
{% endif %}
loop
{% for user in users %}
<li><a href="{{ user.url }}">{{ user.username }}</a></li>
{% endfor %}
loop with range
{% for n in range(n) %}
filters
upper case
var|upper
lower case
var|lower
replace occurrences
var|replace('_', '-')
replace occurrences (with limit)
var|replace('_', '-', 2)
documentation
https://jinja.palletsprojects.com/en/2.11.x/templates/#builtin-filters
documentation
https://jinja.palletsprojects.com/en/2.11.x/
https://jinja.palletsprojects.com/en/2.11.x/templates/