添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接

用Jinja2模板提取嵌套字典

1 人不认可

我有这样的代码,有嵌套的字典,我需要把它放在一个Jinja2模板中,但没有任何运气。

from jinja2 import Template
vlans = {"1": {"description": "default", "name": "default", "IP": {"IP1": "10.0.0.1", "IP2": "20.0.0.2"}}}
vlan_template = Template('''
{% for key,value in vlans.items() %}
vlan {{ key }}
 description {{ value.description }}
 name {{ value.name }}
 {% if value == "IP"%}
  {% for subkey,subvalue in value["IP"].items() %}
  ip address {{ subvalue.IP1 }}
  ip address {{ subvalue.IP2 }} secondary
  {% endfor %}
 {% endif %}
{% endfor %}
print(vlan_template.render(vlans = vlans))

我试图得到以下输出结果

vlan 1 description default name default ip address 10.0.0.1 ip address 20.0.0.2 secondary
python
jinja2
Marius
Marius
发布于 2020-08-02
1 个回答
Marius
Marius
发布于 2020-08-02
已采纳
0 人赞同

我已经设法找到了这个代码

from jinja2 import Template
vlans = {"1": {"description": "default", "name": "default", "IP": {"IP1": "10.0.0.1", "IP2": "20.0.0.2"}}}
vlan_template = Template('''
{%- for key,value in vlans.items() %}
 {%- for k,v in value.items() %}
vlan {{ key }}
 description {{ value.description }}
 name {{ value.name }}
 ip address {{ v.IP1 }}
 ip address {{ v.IP2 }}
 {%- endfor %}
{%- endfor %}
print(vlan_template.render(vlans = vlans))

which gives me 3 times the info but only the 3rd time is correct

vlan 1 description default name default ip address ip address vlan 1 description default name default ip address ip address vlan 1 description default name default ip address 10.0.0.1 ip address 20.0.0.2

问题是,我只想打印

vlan 1 description default