Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 755
user3089927 Avatar asked Aug 18 '14 22:08

user3089927


People also ask

How do you iterate through a list in Jinja?

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.

How do I iterate through a dictionary list?

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.

Can you iterate through dictionaries?

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.

How do you write a for loop in Jinja2?

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.


1 Answers

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.

like image 170
Nava Avatar answered Oct 16 '22 09:10

Nava