Jinja2: Difference between revisions
Jump to navigation
Jump to search
Line 43: | Line 43: | ||
{%- endif %} | {%- endif %} | ||
</syntaxhighlight> | </syntaxhighlight> | ||
This works with empty strings too: | |||
<syntaxhighlight lang='jinja'> | |||
{%if some_var != "" -%} | |||
my var is {{ some_var }} | |||
</syntaxhighlight> | |||
To check whether a variable is defined or not defined: | To check whether a variable is defined or not defined: | ||
<syntaxhighlight lang='jinja'> | <syntaxhighlight lang='jinja'> |
Revision as of 23:02, 2 March 2022
External
- https://medium.com/knoldus/jinja2-template-the-modern-design-friendly-templating-engine-a9218fec96e5
- https://jinja.palletsprojects.com/en/2.11.x/
- https://pypi.org/project/Jinja2/
Internal
Overview
Programming Model
Find out what the latest version is from https://pypi.org/project/Jinja2/
Then add this to your requirements.txt
jinja2 == 3.0.3
Once the virtual environment is updated, use it as such:
from pathlib import Path
from jinja2 import Environment, FileSystemLoader
template_dir = Path('...')
yaml = Environment(loader=FileSystemLoader(template_dir))\
.get_template('my-template.yaml.j2') \
.render(variable_1='some value', variable2='some other value')
Templating Language
Variable
raw content followed by {{ variable1 }}
Conditional
{%if some_var == "something" -%}
something
something else {{ var_1 }}
{% else %}
something completely different {{ var_2 }}
{%- endif %}
This works with empty strings too:
{%if some_var != "" -%}
my var is {{ some_var }}
To check whether a variable is defined or not defined:
{%if some_var is defined -%}
something
{%- endif %}
{%if some_var is not defined -%}
something else
{%- endif %}
Whitespace Management
A leading dash removes all whitespace (including new lines) between the last non space template character and it. A trailing dash removes all whitespace (including new lines) between it and the next non-whitespace character from the template.
{{-
-}}
{%-
-%}