Jinja templating - Iterating through a dictionary which is item in a list

Viewed 12

Wondering if anyone can help with some Jinja looping!

I have a dataset called game_hints_list which is an object property of a ‘game’ class. This list has a total of three items, each of which is a dictionary:

[{'q': 'blank', 'w': 'blank', 'e': 'blank', 'r': 'blank', 't': 'blank', 'y': 'blank', 'u': 'blank', 'i': 'blank', 'o': 'blank', 'p': 'blank'}, {'a': 'blank', 's': 'blank', 'd': 'blank', 'f': 'blank', 'g': 'blank', 'h': 'blank', 'j': 'blank', 'k': 'blank', 'l': 'blank'}, {'z': 'blank', 'x': 'blank', 'c': 'blank', 'v': 'blank', 'b': 'blank', 'n': 'blank', 'm': 'blank'}]

I have checked the types of the list and the items and they are confirmed as being a ‘list’ and ‘dict’ respectively.

In the front end I want to iterate through each dictionary in the list ‘individually’. So in the front end I want to loop through index[0], then index[1], then [2], accessing the key and values for each. This is where I am having the issue.

I can iterate through all three dictionaries displaying the k:v for each as below:

{% for dict in game.game_hints_list %}
    {% for key, value in dict.items() %}
        <p>{{ key }}:{{ value }}</p>
    {% endfor %}
{% endfor %}

This results in the below in the browser:

q:blank
w:blank
e:blank
r:blank
t:blank
y:blank
u:blank
i:blank
o:blank
p:blank
a:blank
s:blank
d:blank
f:blank
g:blank
h:blank
j:blank…
……..

So I figured that the below would work:

{% for key, value in game.game_hints_list[0].items() %}
    <p>{{ key }}:{{ value }}</p>
{% endfor %}

However, when I run this I get the browser displayed error:

UndefinedError: jinja2.exceptions.UndefinedError: list object has no element 0

But, when I try

{{ game.game_hints_list[0] }}

I do not get an error and the dict in item[0] displays:

{'q': 'blank', 'w': 'blank', 'e': 'blank', 'r': 'blank', 't': 'blank', 'y': 'blank', 'u': 'blank', 'i': 'blank', 'o': 'blank', 'p': 'blank'}

So why am I getting this error and how do I iterate through each dictionary individually?

1 Answers

Solved this. The list was not populating initially and so had to add a conditional to check for the presence of [index] before trying to iterate through it.

Related