Reputation: 1114
I'm currently building small manager (learning python) using Pythons Flask, which uses the Jinja2 template engine. I'm using Peewee to talk to my database.
I have a dictionary of pins, which all contains info on the given pin. The info on the pins comes directly from Peewee, like so:
pins = {}
pins[3] = Pin.get(Pin.id == 3)
pins[5] = Pin.get(Pin.id == 5)
pins[7] = Pin.get(Pin.id == 7)
pins[8] = Pin.get(Pin.id == 8)
(Only using these four as an example)
In my template I'm iterating through these four pins and would like to display my DB information (e.g. Description, state and id), so I've written this code:
{% for pin in pins %}
{% if pin.state %}
<input type="checkbox" checked="checked" data-toggle="toggle" data-pin="{{ pin.id }}">
{% else %}
<input type="checkbox" data-toggle="toggle" data-pin="{{ pin.id }}" ?>
{% endif %}
{{ pin.description }}
<br>
{% endfor %}
According to the jinja2 website and this question the code should work, since I'm accessing pin.state, pin.id and pin.description inside the loop.
But it doesn't - No matter which property I try to show, it just gives me nothing when using {{ pin.description }}
to access the property. I've noticed the following, which may give some help
{{ pin }}
inside the loop it prints the current key of
the dictionary.{{ pins[pin].description }}
inside the loop it prints the
correct description. According to my understanding of the documentation and the linked question, it should be possible to show the current values, using {{ pin.description }}
inside the loop.
Can anyone shed some light on what my mistake is?
Upvotes: 0
Views: 164
Reputation: 599480
The issue is that you have made a dictionary, not a list. When you iterate through a dictionary via for pin in pins
, you are iterating through the keys, not the values - so in each iteration you get one of 3, 5, 7 etc. Those values obviously don't have properties like description
.
Instead, use the values()
method:
{% for pin in pins.values() %}
Or you might consider just using a list in the first place.
Upvotes: 1