1

I have dictionary formate like :

uri_dict :{
"152.2.3.4" : ["/v1/draft" , 2],
"172.31.13.12" : ["/v1/url" , 34]
}

I want to render this in django template in tabular formate:

{% for keys, value in url_dict.items %}
                      <tr border = 1px black> 
                        <th>{{ keys }}</th>
                        <td> {{ value[0] }} </td>      <!--requires value[0]  but not working -->
                        <td>{{ value[1]}} </td>   <!--not working -->
                        </tr>
                        {% endfor %} 

Please provide me any solution--- how to iterate over list values in template? How to iterate over list values

Anil Arya
  • 3,100
  • 7
  • 43
  • 69

3 Answers3

2

There are a few options:

<td>{{ value.0 }}</td>
<td>{{ value.1 }}</td>

{% for item in value %}
    <td>{{ item }}</td>
{% endfor}

These two are covered in my comment (and the other answers after it). For a list of length 2 you can also:

<td>{{ value|first }}</td>
<td>{{ value|last }}</td>
Paulo Scardine
  • 73,447
  • 11
  • 124
  • 153
1

To access array elements on a django template you must refer to them as elem.attribute.

In your case, value.0 and value.1.

{% for keys, value in url_dict.items %}
<tr border = 1px black> 
    <th>{{ keys }}</th>
    <td>{{ value.0 }}</td>   <!--requires value[0]  but not working -->
    <td>{{ value.1 }}</td>   <!--not working -->
</tr>
{% endfor %} 

This page may help you: How to access array elements in a Django template?

Hope this helps,

Community
  • 1
  • 1
Miquel
  • 858
  • 11
  • 20
1

If you always have only two items on the each value of dictionary, which are lists, then

{% for keys, value in url_dict.items %}
     <tr border = 1px black> 
         <th>{{ keys }}</th>
             <td> {{value.0}}</td>
             <td> {{value.1}}</td>
     </tr>
{% endfor %} 

If there can be any number of items on list, then just loop for each items:

{% for keys, value in url_dict.items %}
     <tr border = 1px black> 
         <th>{{ keys }}</th>
         {% for eachval in value %}
             <td> {{ eachval}}</td>
         {% endfor %}
     </tr>
{% endfor %} 
Santosh Ghimire
  • 3,087
  • 8
  • 35
  • 63