sharataka
sharataka

Reputation: 5132

How do I use a for loop in a django template?

In my django view, I have a list that looks like the above (except 50 lists embedded within the big list. In my template, how do I use a for loop to reference to display each of the elements within every list?

I am also trying to access a particular element within a list, for example the element 'c' in the below example. I tried feed[0][1] in the template but received an error.

feed = [ [0,a,b,c], [1,d,e,f], ... ] 

{% for video in feed %}
#not sure what to put here
{% endfor %}

Upvotes: 2

Views: 149

Answers (2)

Juan Condori Olivo
Juan Condori Olivo

Reputation: 11

I use

 {%for D in TablePivot %}
     <tr class="{% cycle row1,row2 %}">
        {%for valor in D %}
        <td>{{valor}}</td>
        {%endfor%}
    </tr>
 {%endfor%}

Upvotes: 1

Rohan
Rohan

Reputation: 53386

Something like this:

{% for video in feed %}
    {%for item in video %}
         {{item}} {% comment %} render it appropriately {% endcomment %}
    {%endfor%}
{% endfor %}

video is again a list so you can again iterate over it to get item in it and use it to render appropriate html.

EDIT: With reference to comment by #jdi and updated question, if you want to access particular element of list you can do:

{% video in feed %}
    {{ video.3 }}    {% comment %} To access 3rd element {% endcomment %}
    {{ video|last }} {% comment %} To access last element {% endcomment %}
{%endfor%}

Upvotes: 3

Related Questions