Using Jinja2
Using Jinja 2 with FileSystem Templates#
Install jinja
pip install jinja2
In your file import required stuff
from jinja2 import Environment, FileSystemLoader
Create a folder called templates and add a file called config.j2
{% for customer in customers %}
set groups {{ customer[‘group’] }} interfaces {{ customer[‘interface’] }} unit {{ customer[‘unit’] }} {{ line }}
{% endfor %}
Create the environment
env = Environment(
loader=FileSystemLoader('templates'),
trim_blocks=True,
lstrip_blocks=True
)
Get the template
template = env.get_template('config.j2')
Render the template with a context dict
print(template.render(customers=[
{
'group': 'lx-1',
'interface': 'ae16',
'unit': '556'
},
{
'group': 'lx-2',
'interface': 'ae16',
'unit': '557'
},
]))
Removing / Managing Indentation#
We are concerned about 2 variables trim_blocks and lstrip_blocks:
- trim_blocks: If this is set to True the first newline after a block is removed (block, not variable tag!). Defaults to False
-
lstrip_blocks: If this is set to True leading spaces and tabs are stripped from the start of a line to a block. Defaults to False
env = Environment( loader=FileSystemLoader(‘templates’), trim_blocks=True, lstrip_blocks=True )
Read the docs: Jinja: Template Designer Documentation
Do Not Compute Inside the Template#
The only way to append to a list in a template is an append-and-return-nothing
hack, because {{ }} prints whatever the expression returns:
{% set policy_list = [] %}
{% for ip in host_ip %}
{{ policy_list.append(ip) or "" }}
{% endfor %}
It works, and it is a signal that the data should have been assembled in Python
before the render call. {% set %} is for a label or a local value, not for
carrying state across a loop: a template that mutates its own context is hard to
read and impossible to unit test on its own.