Updating snippet count
Now that you have tried the `for` loop, lets up-level. In this part we will try `if` and `set` statement along with `for` loops.
-
-
First, we want to start the Python interpreter and import `Template` module from Jinja2 library:
```
@@ -15,7 +13,6 @@ from jinja2 import Template
Here we are redefining `interface`, the list of dictionaries we defined in part 2.
-
```
interfaces = [{'interface': 'ge-0/0/0', 'ip_address': '192.168.1.1'},
{'interface': 'ge-0/0/1', 'ip_address': '10.10.1.1'},
@@ -27,8 +24,11 @@ interfaces = [{'interface': 'ge-0/0/0', 'ip_address': '192.168.1.1'},
In Part2, generated configurations for all interfaces in the list. But what if you are only interested in generating the configuration for the management IP address? That is when we use the Jinja2 filters. For this particular example we will be using the `if` condition. It is similar to the python `if` condition, except for the syntax.
Below is the Jinja2 syntax for `if statement` for checking conditions:
- `{% if condition %} ... {% endif %}`
-
+```
+{% if condition %}
+ ...
+{% endif %}
+```
In the following snippet we have used the `for` loop like in previous stages, but instead of directly printing out all the interfaces here we are checking if the interface value matches our management interface `fxp0`. If it does match, we substitute its value and the value of the corresponding ip address in the template using `template.render()`.
```
@@ -51,7 +51,7 @@ render_1 = ipaddr_template.render(interfaces=interfaces)
print(str(render_1))
```
-<button type="button" class="btn btn-primary btn-sm" onclick="runSnippetInTab('linux1', 2)">Run this snippet</button>
+<button type="button" class="btn btn-primary btn-sm" onclick="runSnippetInTab('linux1', 3)">Run this snippet</button>
The output shows that it just printed the entry of the management interface. Thus we learnt the power of `if` statements to filter out our data based on certain conditions.
@@ -61,7 +61,9 @@ A better approch is to define a variable called `mgmt_interface` and, change the
Jinja2 uses set statement to define variable which can be used within the template. The syntax is defined below:
- `{% set variable_name: variable_value %}`
+```
+{% set variable_name: variable_value %}
+```
In the snippet below:
`set_temp = '''{% set mgmt_interface = 'ge-0/0/0' %}` declares a variable `mgmt_interface` and sets its value to `ge-0/0/0`.
@@ -90,6 +92,6 @@ render_2 = int_template.render(interfaces=interfaces)
print(str(render_2))
```
-<button type="button" class="btn btn-primary btn-sm" onclick="runSnippetInTab('linux1', 3)">Run this snippet</button>
+<button type="button" class="btn btn-primary btn-sm" onclick="runSnippetInTab('linux1', 5)">Run this snippet</button>
In the next stage, we'll dive deeper into using YAML files for defining variables for Jinja2 templates.
