簡體   English   中英

如何在 jinja2 模板中使用嵌套變量

[英]How to use nested variables in jinja2 templates

如何在 jinja 模板中使用項目的嵌套變量? 我正在運行 ansible 為網絡交換機生成配置。

試圖讓 if 語句基於 bgp_peer_version,

我有以下變量文件

 ---
 switches:
   - ansible_hostname: Core1
     bgp_neighbors:
       - bgp_peer_version: both
         bgp_peer_ipv4: 10.1.1.1
         bgp_peer_ipv6: 2001::1
         bgp_vrf:
       - bgp_peer_version: v4
         bgp_peer_ipv4: 10.1.1.2
         bgp_peer_ipv6: 
         bgp_vrf:

   - ansible_hostname: Core2
     bgp_neighbors:
       - bgp_peer_version: 'both'
         bgp_peer_ipv4: 10.1.1.2
         bgp_peer_ipv6: 2001::1
         bgp_vrf:
       - bgp_peer_version: 'v4'
         bgp_peer_ipv4: 10.1.1.2
         bgp_peer_ipv6:
         bgp_vrf: 

到目前為止有以下代碼

{% if item[bgp_peer_version] == "v4" %}
BGP Peer
IPv4 address {{ bgp_peer_ipv4 }}
{% else %}
BGP Peer
IPv4 address {{ bgp_peer_ipv64 }}
IPv6 address {{ bgp_peer_ipv6 }}
{% endif %}

我正在嘗試構建一個模板,該模板使用每個交換機的 bgp 鄰居中的變量。 我正在尋找帶有第一個模板的 output。 模板 1 output

BGP 對等 IPv4 地址 10.1.1.1 IPv6 地址 2001::1 BGP 對等 IPv4 地址 10.1.1.1

模板 2 output

BGP 對等 IPv4 地址 10.1.1.2 IPv6 地址 2001::2 BGP 對等 IPv4 地址 10.1.1.1

問: “我如何在 jinja 模板中使用嵌套變量(項目的)?”

A:這可能是你要找的嗎?

{% for item1 in switches %}
{% for item in item1 %}
{% if item[bgp_peer_version] == "v4" %}
result is V4
{% else %}
result if both
{% endif %}
{% endfor %}
{% endfor %}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM