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 variablexxx
exists, or istrue
-
"xxx" in variable
: true ifvariable
containsxxx
-
"xxx" not in variable
: false ifvariable
containsxxx
-
variable in ["xxx", "yyy"]
: true ifvariable
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 %}