LewisCallaway
LewisCallaway

Reputation: 53

Trouble with python dictionaries and iterating through them with Jinja

I have a Python dictionary that looks like this. {0: {'record': u'running fast', 'moreInfo': u'test', 'year': u'2017', 'name': u'Jose la computadora', 'activity': u'Cross Country'}, 1: {'record': u'test', 'moreInfo': u'ttt', 'year': u'2000', 'name': u'Lewdog', 'activity': u'Cross Country'}}

I'm passing it to a Jinja template with Flask. The dictionary is set to the variable databaseQuery and passed to Jinja. My jinja code looks like this, but nothing shows up on the page. If I print databaseQuery on the page, I get the whole dictionary, and if I print test, I just get 0 1. I'm trying to figure out how to iterate through my dictionary and show each value for name on the page.

{% for test in databaseQuery %}
{{test["name"]}}
{% endfor %}

I've looked at this list of dictionary in jinja template but didn't have any luck.

Thanks!

Upvotes: 0

Views: 701

Answers (3)

cp151
cp151

Reputation: 197

Hei ;

With python iterating over a dict gives you the key.

a = {1:'test'}
for k in a 

will give you 1

Try a[key] to access the values

Edit :

{% for test in databaseQuery %}         
{{databaseQuery[test]}}
{% endfor %}

Upvotes: 0

user2390182
user2390182

Reputation: 73490

Iterating a dict produces only the keys. You can do:

{% for k in databaseQuery %}
    {{ databaseQuery[k]['name'] }}
{% endfor %}

Or:

{% for k, v in databaseQuery.items() %}
    {{ v['name'] }}
{% endfor %}

Upvotes: 0

mclslee
mclslee

Reputation: 498

Well you're just iterating through the keys of databaseQuery.

Jinja suppresses some errors so that's why it's not exploding for you.

This isn't a Jinja issue but a python issue; if you iterate through a dictionary without specifying keys, values or items, it'll just loop through the keys, which for you are 0 and 1 which are just integers.

If you want to access just the values, you could do

{% for val in databaseQuery.values() %}
    {{ val['name'] }}
{% endfor %}

should get you what you want. It's worth noting unless those integers (0 and 1) will be used for something meaningful, you could just pass up the list of dictionaries and loop through that as you did and that would work.

Upvotes: 1

Related Questions