Rendering is changing data into something <variable> -------> into "value".
Parsing takes raw data or input and converts it a data structure, or structures that can be analyzed.
Jinja2 - 101 - Intro to Jinja2 template building
|
|
---|
|
With Python: ( use extensively by Ansible)
>>> from jinja2 import Template
>>> template = Template('Hello {{ name }}!')
>>> template.render(name='John Doe')
'Hello John Doe!'
|
|
ymlvariablefile = ''
jinja2templatefile = ''
# the checkargument function, only make sure the arg( file names) have been passed on.
ymlvariablefile ,jinja2templatefile = checkargument(argv)
#print("yml:", ymlvariablefile ,"\nj2: ",jinja2templatefile)
#Load data from YAML into Python dictionary
config_data = yaml.load(open(ymlvariablefile))
#Load Jinja2 template from the dirctory called: templates
j2_env = Environment(loader = FileSystemLoader('./templates'), trim_blocks=True, lstrip_blocks=True)
template = j2_env.get_template(jinja2templatefile)
#Render the template with data and print the output
print(template.render(config_data))
print("###################################################")
print("\tyml:", ymlvariablefile, "\n\tj2: ", jinja2templatefile)
print("La FIN")
from jinja2 import Template
def render_jinja2():
with open(r"C:\Users\jkriker\Documents\GitHub\JAUT_Training\Basic-python-with-Juniper\Napalm\config_unit.j2") as file_:
template = Template(file_.read())
print(template.render(unit_id='5', vlan_id=5, subnet="0.5"))
render_jinja2(template_name, list_variables)
Example using it: https://github.com/dahai0013/Basic-python-with-Juniper/tree/master/Napalm |
|
import jinja2
def render_j2():
templateLoader = jinja2.FileSystemLoader(searchpath = r"C:\Users\jkriker\Documents\GitHub\JAUT_Training\Basic-python-with-Juniper\Napalm" )
templateEnv = jinja2.Environment(loader=templateLoader)
TEMPLATE_FILE = "config_unit.j2"
template = templateEnv.get_template(TEMPLATE_FILE)
outputText = template.render(unit_id=5, vlan_id=5, subnet="0.5")
print(outputText)
|
|
from jinja2 import Environment, FileSystemLoader
def render_config(config_template):
file_loader = FileSystemLoader(r"C:\Users\jkriker\Documents\GitHub\JAUT_Training\Basic-python-with-Juniper\Napalm")
env = Environment(loader=file_loader)
template = env.get_template("config_unit.j2")
output = template.render(unit_id="5", vlan_id="5", subnet="0.5")
print(output)
|
|
|
|
|
|
|