Skip to content

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(

Get the template

template = env.get_template('config.j2')

Render the template with a context dict

        '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 )