添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
我有这个带有嵌套字典的代码,我需要在没有任何运气的情况下放入 jinja2 模板中......from jinja2 import Templatevlans = {"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#谢谢,马吕斯。
查看完整描述

TA贡献1828条经验 获得超3个赞

我已经设法得到这个代码


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))

这给了我 3 倍的信息,但只有第 3 次是正确的


#

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

name default

ip address 10.0.0.1

ip address 20.0.0.2

#


查看完整回答