Jinja2

From NovaOrdis Knowledge Base
Jump to navigation Jump to search

External

Internal

TODO

What happens if a document containing a variable is rendered and the variable value is not provided?

Overview

Playground

https://github.com/ovidiuf/playground/tree/master/pyhton/jinja2

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('...')
text = Environment(loader=FileSystemLoader(template_dir))\
  .get_template('my-template.yaml.j2') \
  .render(variable_1='some value', variable_2='some other value')

If the content is already loaded:

template_as_text = '...'
rtemplate = Environment().from_string(template_as_text)
data = rtemplate.render(variable_1='some value', variable_2='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 %}

Loops

my_list:
  {%- for i in seq %}
  - '{{ i }}'
  {%- endfor %}

where seq is a Python list:

seq = ['a', 'b']
text = Environment(loader=FileSystemLoader(template_dir)).get_template('my-template.yaml.j2').render(seq=seq)

Rendering Dictionaries

from jinja2 import Environment

template_as_text = '''
something:
{%- for key, value in a_dict.items() %}
    {{key}}: {{value-}} 
{% endfor %}
somethingelse
'''
a_dict = {'a': 'A', 'b': 'B', 'c': 'C'}
rtemplate = Environment().from_string(template_as_text)
data = rtemplate.render(a_dict=a_dict)
print(data)

This will render:

something:
    a: A
    b: B
    c: C
somethingelse

Rendering Embedded Maps

If a complex recursive data structure, such as embedded maps, is passed to render(), an arbitrary level key can be accessed with the dot notation:

m = {
    'm1': {
        'color': 'red'
    },
    'm2': {
        'color': 'blue'
    }
}

template_as_text = '''
color: {{ m.m1.color }}
'''
rtemplate = Environment().from_string(template_as_text)
data = rtemplate.render(m=m)
print(data)

will print:

color: red

Rendering an Object's __str__() Representation

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.

 {{-
 -}}
 {%-
 -%}

Filters

Filters