I tried:
list1 = [{"username": "abhi", "pass": 2087}] return render_template("file_output.html", list1=list1)
In the template:
<table border=2> <tr> <td> Key </td> <td> Value </td> </tr> {% for dictionary in list1 %} {% for key in dictionary %} <tr> <td> <h3>{{ key }}</h3> </td> <td> <h3>{{ dictionary[key] }}</h3> </td> </tr> {% endfor %} {% endfor %} </table>
The above code is splitting each element into multiple characters:
[ { " u s e r ...
I tested the above nested loop in a simple Python script and it works fine but not in Jinja template.
To iterate through a list of dictionaries in Jinja template with Python Flask, we use a for loop. to create the parent_list list of dicts. in our Jinja2 template to render the parent_list items in a for loop.
In Python, to iterate the dictionary ( dict ) with a for loop, use keys() , values() , items() methods. You can also get a list of all keys and values in the dictionary with those methods and list() . Use the following dictionary as an example. You can iterate keys by using the dictionary object directly in a for loop.
You can loop through a dictionary by using a for loop. When looping through a dictionary, the return value are the keys of the dictionary, but there are methods to return the values as well.
Jinja2 being a templating language has no need for wide choice of loop types so we only get for loop. For loops start with {% for my_item in my_collection %} and end with {% endfor %} . This is very similar to how you'd loop over an iterable in Python.
parent_list = [{'A': 'val1', 'B': 'val2'}, {'C': 'val3', 'D': 'val4'}]
{% for dict_item in parent_list %} {% for key, value in dict_item.items() %} <h1>Key: {{key}}</h1> <h2>Value: {{value}}</h2> {% endfor %} {% endfor %}
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With