TYL
TYL

Reputation: 83

Django/Jinja2: How to use the index value in a for-loop statement to display two lists?

I'm trying to display the items from two lists. This is my code:

#Django view.py file
def display(request):
   listone = ['duck', 'chicken', 'cat', 'dog']
   lents = len(list_one)
   listtwo = ['4 dollars', '3 dollars', '2 dollars', '1 dollars']
   return render(request, 'display.html', {'itemone' : listone, 'itemtwo' : listtwo, 'lents' : lents})

This is the display.html template that displays the lists:

<table>
   <tr>
     <th>Pet</th>
     <th>Price</th> 
   </tr>
   {% for numbers in lents %}
      <tr>
        <td>{{ itemone.numbers }}</td>
        <td>{{ itemtwo.numbers }}</td>
      </tr>
   {% endfor %}
</table>

but with no luck it won't show the result according to the index 'numbers' which suppose to be from '0' to '3', the td tags remaining empty.

Upvotes: 2

Views: 1013

Answers (1)

PRMoureu
PRMoureu

Reputation: 13327

A better option is to create a zip object in your view, to match the pet to a price, and pass only this to the template :

def display(request):
   listone = ['duck', 'chicken', 'cat', 'dog']
   listtwo = ['4 dollars', '3 dollars', '2 dollars', '1 dollars']
   fusion = zip(listone, listtwo)
   return render(request, 'display.html', {'fusion' : fusion})

Then you can unpack it in your template, zip() will produce a list of tuples (name, price) and you can easily loop on this :

<table>
   <tr>
     <th>Pet</th>
     <th>Price</th>
   </tr>
   {% for name, price in fusion %}
      <tr>
        <td>{{ name }}</td>
        <td>{{ price }}</td>
      </tr>
   {% endfor %}
</table>

Another solution is to create a new custom template filter, there are already some posts explaining the process : https://stackoverflow.com/a/29664945/6655211

Upvotes: 2

Related Questions