Strobe_
Strobe_

Reputation: 515

Accessing nested dictionary using Jinja2 templating

So I have this list of dictionaries:

mylist = [{'Score': 33, u'interfaces': [{u'ip_addresses': [{u'value': u'172.16.153.71', }]}]}]

I want to access the 'value' key using jinja2.

However, I just can't seem to get the syntax right for it. I know it'll probably be three for loops inside each other, but I can't get it right.

I can do it in python like:

for i in mylist:
  for x in i['interfaces']:
    for y in x['ip_addresses']:
      print y["value"]

So maybe something like this?:

            {% for obj in mylist %}
              {%for obj2 in obj %}
                {for obj3 in obj2 %}
                    {{ obj3.value }}",
                {% endfor % }
              {% endfor % }
            {% endfor % }

But that doesn't work obviously. Any help would be greatly appreciated. Thanks.

Upvotes: 2

Views: 6236

Answers (1)

larsks
larsks

Reputation: 311387

Let's compare your Python loop to your Jinja loop. The outer Python loop is:

for i in mylist:

And the corresponding Jinja loop is:

{% for obj in mylist %}

That looks fine. But while your next Python loop looks like:

for x in i['interfaces']:

Your corresponding Jinja loop is:

{%for obj2 in obj %}

That's obviously not doing the same thing; and since you already have the logic from your Python loop it's not clear why you made this change. The equivalent loop would be:

{% for obj2 in obj.interfaces %}

Or:

{% for obj2 in obj['interfaces'] %}

...which more closely matches the Python, but is less idiomatic for Jinja. You have the same issue with the next nested loop.

If you rewrite your JInja loops to simply follow the Python logic you should be all set.

Upvotes: 2

Related Questions