Jinja2

Jinja is a template engine. We will use Jinja syntax in static files such as HTML or XML files. We then use Jinja to process our templates and generate the resulting file.


Print a variable

You can use {{ a_variable }} almost anywhere to echo a variable:

<some_tag>{{ xxx }}</some_tag>
<some_tag xxx="{{ xxx }}">...</some_tag>

Variables

You can declare variables using set:

{%- set xxx = "Hello, " + "World!" -%}

You can apply transformations on a variable using |:

{{ xxx|upper }}

Branching

You can use if/elif/else/endif. Common conditions are

  • xxx: true if a variable xxx exists, or is true
  • "xxx" in variable: true if variable contains xxx
  • "xxx" not in variable: false if variable contains xxx
  • variable in ["xxx", "yyy"]: true if variable is in the array

Another example: {% if variable %}xxx {% endif %} which optionally shows xxx based on a variable.

{% if "xxx" in variable %}
        Hello, from XXX.
{% elif "yyy" not in variable %}
        Hello, not from YYY.
{% else %}
        Hello.
{% endif %}