Ansible Jinja2模板:能否在for循环内嵌套if语法选择迭代字典?
Absolutely, you can pull this off! The issue with your current code is that you’re trying to nest Jinja2 template tags ({% ... %}) inside each other, which isn’t valid syntax. Instead, you need to first figure out which dictionary to use based on your condition, then iterate over it. Here are two clean, working approaches:
Option 1: Use a Variable to Store the Target Dictionary
This method is super readable, especially if your condition might get more complex down the line:
{% set target_dict = abc if source == "cde" else def %} {% for item, value in target_dict.items() %} {{ item }} {# You can also include the value if needed: {{ item }}: {{ value }} #} {% endfor %}
Option 2: Use a Ternary Expression Directly in the For Loop
If you prefer a concise one-liner, embed the conditional straight into the loop statement:
{% for item, value in (abc.items() if source == "cde" else def.items()) %} {{ item }} {% endfor %}
Quick Note:
If you’re using an older Python version (pre-3.x) where dictionaries use iteritems() instead of items(), just swap items() with iteritems() in either example above.
The key here is resolving the conditional first to get the right iterable, then passing that to the for loop—instead of trying to nest template tags, which Jinja2 doesn’t support.
内容的提问来源于stack exchange,提问作者Jatinder Jawanda

