Home > Blockchain >  Jinja2 render is not replacing variables with values
Jinja2 render is not replacing variables with values

Time:12-01

I have the following problem: key/values:

..
link_1: ge0/0/1
link_2: ge0/0/2
link_3: ge0/0/3
link_4: ge0/0/4

jinja2 template:

..
{%- for index in range(1,5) %}
  {% set line = ['link_',index]|join %}  
  set interface {{line}} speed 1g
{% endfor %}

I expected that in the rendered file I get the values instead of the key's, but I get this output:

..
set interface link_1 speed 1g
set interface link_2 speed 1g
set interface link_3 speed 1g
set interface link_4 speed 1g

The python code to render is more or less this one:

#!/usr/bin/env python3
from jinja2 import Environment, FileSystemLoader
import yaml

kvdata = yaml.load(open('test.yml'))
env = Environment(loader = FileSystemLoader(''))
template = env.get_template('test.j2')

print(template.render(kvdata))

CodePudding user response:

my python program:

str = """
 {"link_1": "ge0/0/1", "link_2": "ge0/0/2", "link_3": "ge0/0/3", "link_4": "ge0/0/4"}
"""
kvdata = json.loads(str)
env = Environment(loader = FileSystemLoader(''))
template = env.get_template('test.j2')

print(template.render(var=kvdata))

my test.j2:

{% for v in var %}
set interface {{var[v]}} speed 1g
{% endfor %}

result:

set interface ge0/0/1 speed 1g

set interface ge0/0/2 speed 1g

set interface ge0/0/3 speed 1g

set interface ge0/0/4 speed 1g

CodePudding user response:

Unfortunately, I was not able you bring your solution working, I used now the following solution:

{% set myLinkDict = ({link_1: 'ge0/0/1', link_2: 'ge0/0/2', link_3: 'ge0/0/3', link_4: 'ge0/0/4'}) %}
{% for link, port in myLinkDict.items() -%}
 set interface {{ port }} speed 1g
{% endfor -%}
  • Related