Jinja2 Loops

Example !

#### Script1 ####

from __future__ import unicode_literals, print_function
from jinja2 import FileSystemLoader, StrictUndefined
from jinja2.environment import Environment

env = Environment(undefined=StrictUndefined)
env.loader = FileSystemLoader([".", "./templates/"])

var_interfaces = {}

var_template_file = "intf_config1.j2"
var_template = env.get_template(var_template_file)
var_output = var_template.render(**var_interfaces)
print(var_output)


#### template #### Single for loop, range can be set like (#) or a range (#,#)
{%- for var_port_number in range(0, 25) %}
interface GigabitEthernet0/1/{{ var_port_number }}
!
{%- endfor %}





---
#### Script2 ####

from __future__ import unicode_literals, print_function
from jinja2 import FileSystemLoader, StrictUndefined
from jinja2.environment import Environment

env = Environment(undefined=StrictUndefined)
env.loader = FileSystemLoader(".")

base_intf = "GigabitEthernet0/1/"
intf_list = []
for intf_number in range(24):
    intf_name = f"{base_intf}{intf_number}"
    intf_list.append(intf_name)

intf_vars = {"intf_list": intf_list}

template_file = "intf_config2.j2"
template = env.get_template(template_file)
output = template.render(**intf_vars)
print(output)


#### template ####
{%- for intf in intf_list %}
interface {{ intf }}
 switchport access vlan 400
 switchport mode access
!
{%- endfor %}




---
#### Script3 ####

from __future__ import unicode_literals, print_function
from jinja2 import FileSystemLoader, StrictUndefined
from jinja2.environment import Environment

env = Environment(undefined=StrictUndefined)
env.loader = FileSystemLoader(".")

intf_vars = {}

template_file = "intf_config3.j2"
template = env.get_template(template_file)
output = template.render(**intf_vars)
print(output)

---
####### Nested for loops
{%- for slot in range(1, 4) %}
  {%- for port_number in range(1, 25) %}
interface GigabitEthernet0/{{ slot }}/{{ port_number }}
  {%- endfor %}
{%- endfor %}

####### For loop with conditional
{%- for port_number in range(1, 25) %}
  {%- if port_number == 10 %}
interface GigabitEthernet0/1/{{ port_number }}
  {%- endif %}
{%- endfor %}

######## Jinja2 comment
{# This is a comment in Jinja2 #}


******** more example *********


from __future__ import unicode_literals, print_function
from jinja2 import FileSystemLoader, StrictUndefined
from jinja2.environment import Environment

env = Environment(undefined=StrictUndefined)
env.loader = FileSystemLoader(".")

base_intf = "GigabitEthernet0/1/"
intf_list = []
for intf_number in range(24):
    intf_name = f"{base_intf}{intf_number}"
    intf_list.append(intf_name)

intf_vars = {"intf_list": intf_list}

template_file = "intf_config2.j2"
template = env.get_template(template_file)
output = template.render(**intf_vars)
print(output)

#template 
{%- for intf in intf_list %}
interface {{ intf }}
 switchport access vlan 400
 switchport mode access
!
{%- endfor %}











Leave a Comment