geeknet
geeknet

Reputation: 77

nested for loops in jinja2 template

I want to parse a yml file with a jinja2 template by an ansible playbook, and can not get inner array ('items' in the example below) with nested 'for':

There is YML:

entities:
 - name: entity1
   desc: "entity 1 description"
   items:
     - desc: "item 11 description"
       name: item11
     - desc: "item 12 description"
       name: item12
 - name: entity2
   desc: "entity 2 description"
   items:
     - desc: "item 21 description"
       name: item2

There is template:

{% for i in entities %}

entity: {{ i.name }}
{% if i.desc is defined %} desc: {{ i.desc }} {% endif %}

{% if i.items is defined %}
items:
{% for j in i.items %}
- name: {{ j.name }}
- desc: {{ j.desc }}
{% endfor %}
{% endif %}

{% endfor %}

This line seems to be incorrect ('builtin_function_or_method object is not iterable'):

{% for j in i.items %}

Is there a way to iterate over the 'items' array?

Upvotes: 0

Views: 1683

Answers (1)

flyx
flyx

Reputation: 39638

items is a function of a Python dict. To access the value of the key 'items', use

{% for j in i['items'] %}

Upvotes: 1

Related Questions