Jinja2 Base Template

So in the following example we import template from jinja2 and then we define our template : text1 and bgp_config,
Then we use the variable j2_template = and we call the template that we want : in this example config1.
we then create a variable for the output so in this example it will be output and then we render it with the render() command.
then we can print the output.

from jinja2 import Template

text1 = """
this is some template
that has multiple lines
of text in it
"""

config1 = """
router bgp 42
 bgp router-id 10.220.88.20
 bgp log-neighbor-changes
 neighbor 10.220.88.38 remote-as 44
"""

var_j2_template = Template(config1)
var_output = var_j2_template.render()
print(var_output)

************************************************************************************

Another Example with Variable apply at the render commands.

config1 = """
router {{ AS }}
 bgp {{ RID }}
 bgp log-neighbor-changes
 neighbor {{ RMIP1}} remote-as {{ RAS }}
"""

var_j2_template = Template(config1)
var_output = var_j2_template.render(AS=22, RID="1.1.1.1", RMIP1="10.10.10.1", RAS=44)
print(var_output)

************************************************************************************
You could make a dictionnary too :

template_vars = {"bgp_as": 22, "router_id": "1.1.1.1", "peer1": "10.20.30.1"}

j2_template = Template(my_template)
output = j2_template.render(**template_vars)
print(output)

config1 could be replace by a file instead :

filename = "bgp_config.j2"
with open(filename) as f:
    my_template = f.read()



Leave a Comment