How to Iterate Through a List of Dictionaries in Jinja Template

How to iterate through a list of dictionaries in Jinja template?

Data:

parent_list = [{'A': 'val1', 'B': 'val2'}, {'C': 'val3', 'D': 'val4'}]

in Jinja2 iteration:

{% for dict_item in parent_list %}
{% for key, value in dict_item.items() %}
<h1>Key: {{key}}</h1>
<h2>Value: {{value}}</h2>
{% endfor %}
{% endfor %}

Note:

Make sure you have the list of dict items. If you get UnicodeError may be the value inside the dict contains unicode format. That issue can be solved in your views.py.
If the dict is unicode object, you have to encode into utf-8.

Iterating over a list of dictionaries in Jinja2 template

It is much easier to convert your structure to a list of class objects, with the dictionary keys as attributes:

class Item:
def __init__(self, vals):
self.__dict__ = vals

@app.route('/yourroute')
def your_route():
data = [{'name': 'chicken pie', 'image': 'chicken.jpg', 'url': 'chicken.html'}, {'name': 'chicken sandwich', 'image': 'sandwich.jpg', 'url': 'sandwich.html'}]
return flask.render_template('your_template.html', names = [Item(i) for i in data])

Lastly, in your_template.html:

<div class="page-header">
<h1>Recipes Matching {{ query }}</h1>
{% for dict_item in names %}
<div>
<img src="{{dict_item.image}}" height="100" width="100">
<a href="{{dict_item.url}}">{{dict_item.name}}</a>
</div>
{% endfor %}
</div>

Iterating through a python dictionary in flask jinja

Try changing views.py to:

@views.route("/test", methods=["GET"])
@login_required
def test():
countries = Country.query.all()
countriess = []
for country in countries:
countriess.append({country.country_code: country.country_name})

return render_template("TEST.html", user=current_user, countries=countriess)

This code will create a list of dictionaries countries, there is not need to change the templating code.

List of dictionaries in jinja

Try This:-

{% for dict_item in products %}
<h1>Product: {{ dict_item['product'] }}</h1>
<h2>Cost: {{ dict_item['cost'] }}</h2>
{% endfor %}

Ansible: How to iterate through the list of dictionaries using Jinja

The following playbook f.yml

---
- hosts: localhost
connection: local
gather_facts: False
vars:
users:
- name: "user1"
db:
- name: "main"
default_privileges:
tables: ['ALL']
sequences: ['ALL']
functions: ['EXECUTE']
types: ['USAGE']
schema:
- name: "public"
owner: no
default_privileges:
tables: ['ALL']
sequences: ['ALL']
functions: ['EXECUTE']
types: ['USAGE']
- name: "notpublic"
owner: no
default_privileges:
tables: ['ALL']
sequences: ['ALL']
functions: ['EXECUTE']
types: ['USAGE']

- name: "user2"
db:
- name: "main2"
default_privileges:
tables: ['ALL']
sequences: ['ALL']
functions: ['EXECUTE']
types: ['USAGE']
schema:
- name: "public"
owner: no
default_privileges:
tables: ['ALL']
sequences: ['ALL']
functions: ['EXECUTE']
types: ['USAGE']
- name: "nonpublic"
owner: no
default_privileges:
tables: ['ALL']
sequences: ['ALL']
functions: ['EXECUTE']
types: ['USAGE']


tasks:
- name: templating
template:
src: "f.jj"
dest: "f.txt"

with this template f.jj

{% for user in users %}
{% for userdb in user.db %}
{% for s in userdb.schema %}

{{ s.name }}

{% endfor %}
{% endfor %}
{% endfor %}

produces with

$ ansible-playbook f.yml

PLAY [localhost] ***************************************************************

TASK [templating] **************************************************************
ok: [localhost]

PLAY RECAP *********************************************************************
localhost : ok=1 changed=0 unreachable=0 failed=0

the output file f.txt


public


notpublic


public


nonpublic

Jinja2 looping over list of dictionary items

As mentioned above, you can achieve that by modifying your third loop.
To simplify:

list = [{'2020': [''], '2019': ['05'], '2018': ['02', '01']}]

Template:

{% for obj in list %}
{% for obj2 in obj %}
<p>{{ obj2 }}</p>
{% for obj3 in obj[obj2] %}
<p>{{ obj3 }}</p>
{% endfor %}
{% endfor %}
{% endfor %}

Output:

2020   
2019
05
2018
02
01

Iterating through Python dictionary with Jinja2

You can pass dict.items to the template rendering object:

return flask.render_template('template_name', data = the_dict.items())

Then, in the HTML:

{%for a, b in data%}
<span>Key: {{a}}, value: {{b}}</span>
{%endfor%}

jinja2 - loop through a dictionary

The below would create a output with all the user names in it

{% for item in test123.values() %}
name of the user: {{ item.name }}
{% endfor %}

Output format:

name of the user: test1
name of the user: test2

If you need something in specific format let me know the desired output



Related Topics



Leave a reply



Submit