3. Jinja2 Syntax Notes#

3.1. 1. Variables#

{{ EXPRESSION }}

3.2. 2. Conditionals#

{% if EXPRESSION %}
    ...
{% elif EXPRESSION %}
    ...
{% else %}
    ...
{% endif %}

3.3. 3. Loops#

{% for item in items %}
    ...{{ item }}...
{% endfor %}

Loop special variables:

{{ loop.index }}        {# 1-based #}
{{ loop.index0 }}       {# 0-based #}
{{ loop.first }}
{{ loop.last }}

3.4. 4. Template Inheritance#

{% block block_name %}{% endblock %}

{% extends "extended_template_name" %}
#Example:

#layout.html
<!DOCTYPE html>
<html>
<body>
  <h1>Site Header</h1>
  {% block content %}{% endblock %}
</body>
</html>

#webpage.thml
{% extends "layout.html" %}

{% block content %}
  <p>This is the page content.</p>
{% endblock %}

3.5. 5. Including Templates#

{% include "included_file_name.html" %}

3.6. 6. Macros#

{% macro button(text, type="primary") %}
  <button class="{{ type }}">{{ text }}</button>
{% endmacro %}

{{ button("Save") }}
{{ button("Delete", "danger") }}

3.7. 7. Importing Macros#

{% import "macros.html" as ui %}
{{ ui.button("Click me") }}

3.8. 8. Filters#

{{ name | upper }}
{{ text | replace("old", "new") }}
{{ items | length }}
{{ content | safe }}    {# do not escape HTML #}

Common filters:
upper, lower
title
length
replace("a","b")
join(", ")
safe (disable autoescape)
default("value")
../../_images/jinja2-builtin-filters.png

3.9. 9. Set Variables in Template#

{% set total = price * quantity %}
<p>Total: {{ total }}</p>

3.10. 10. Raw Blocks#

{% raw %}
{{ this_will_not_be_rendered }}
{% endraw %}

3.11. 11. Comments#

{# This is a comment and will not appear in output #}

3.12. An jinja2 API example#

import jinja2

env = jinja2.Environment(loader=jinja2.FileSystemLoader("./templates"))
temp = env.get_template("content.html")
html = temp.render(add_block2=True, title="<h1>Test</h1>")
print(html)

3.13. References#

https://jinja.palletsprojects.com/en/stable/templates/

https://jinja.palletsprojects.com/en/stable/api/