Topic: tech juniper jaut prev next
tech juniper jaut > Module 03: Jinja2
#!/usr/bin/python
from jinja2 import Template
template_string = "Hello {{ user }}"
my_template = Template(template_string)
result = my_template.render({"user": "lab"})
print(result)
‘templates’ is the path to the directory where the templates reside. The filename given to ‘get_template’ is now relative to the FileSystemLoader’s directory. This is the recommended way to load templates from files with Jinja2.
#!/usr/bin/python
from jinja2 import Environment, FileSystemLoader
env = Environment(loader=FileSystemLoader("templates"))
my_template = env.get_template("hello.j2")
result = my_template.render({"user": "lab"})
print(result)
#!/usr/bin/python
from jinja2 import Environment, FileSystemLoader
env = Environment(loader=FileSystemLoader("templates"))
my_template = env.get_template("hello.j2")
with open("variables/data.yml") as f:
data = load(f)
result = my_template.render(data)
print(result)
{# this is a comment #}
{%- for user in users %}
{% endfor %}
To access fields in a dictionary, use dictionary[‘field’] or dictionary.field .
To loop over items in a list, use;
{% for user in users %}
To loop over keys and values in a dictionary, use;
{%- for key, value in dictionary.items() %}
Conditional statement;
{%- if interface != 'fxp0.0' %}
{%- endif %}
{%- if var is defined %}
Variables can be modified by filters. ‘lower’ converts a variable to lower case.
{{ interface_id | lower }}
‘include’ can include other Jinja2 templates. It can be used to load different templates depending on the value of a variable. The ‘ignore missing’ option can be used to surpress errors if the requested template file is missing.
The ‘set’ directive can set template variables from within the template code.
---
interfaces:
- name: ge-0/0/0
address: 172...
- name: ge-0/0/1
address: 172...