Anil Arya
Anil Arya

Reputation: 3110

Rendering dictionary having values in list format in django template

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

Upvotes: 1

Views: 1289

Answers (3)

Paulo Scardine
Paulo Scardine

Reputation: 77339

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>

Upvotes: 2

Santosh Ghimire
Santosh Ghimire

Reputation: 3145

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 %} 

Upvotes: 1

Miquel
Miquel

Reputation: 858

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,

Upvotes: 1

Related Questions