Skip to content

Instantly share code, notes, and snippets.

@rdapaz
Created May 17, 2021 01:45
Show Gist options
  • Save rdapaz/3d6346f617dc1763e7151f225f80b8a3 to your computer and use it in GitHub Desktop.
Save rdapaz/3d6346f617dc1763e7151f225f80b8a3 to your computer and use it in GitHub Desktop.
Using Jinja2 Templates
#1 import these classes from jinja2 module
from jinja2 import FileSystemLoader, Environment, Template
from pathlib import Path
from enum import Enum
import re, sys, os
port_data = """
Gi2/0/23|Gi2/0/23: Desc1|130
Gi2/0/21|Gi2/0/21: Desc2|120
Gi2/0/19|Gi2/0/19: Desc3|115
Gi2/0/17|Gi2/0/17: Desc4|111
Gi2/0/18|Gi2/0/18: Desc5|112
Gi2/0/20|Gi2/0/20: Desc6|116
Gi2/0/22|Gi2/0/22: Desc7|121
""".splitlines()
port_data = [x.split('|') for x in port_data if len(x) > 0]
#2 build template
def make_template():
template_text = """
{%- for ifce_name, desc, vlan_id in port_data %}
int {{ifce_name}}
description {{desc|upper}}::{{vlan_id}}
switchport access vlan {{vlan_id}}
{% endfor %}
"""
return template_text
#3 Instantiate environment and call env.from_string passing in the template text
env = Environment()
template = env.from_string(make_template())
#4 Render the template
print(template.render(locals()))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment