2

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.

PRMoureu
  • 12,817
  • 6
  • 38
  • 48
TYL
  • 83
  • 1
  • 1
  • 7
  • 1
    I am not positive on this, but I don't think Jinja knows what `lents` is because you are not passing it to the template, you are just sending a dict. Maybe try storing that dict you are passing in a variable and then pass that variable to the template. – kstullich Oct 01 '17 at 22:04

1 Answers1

2

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

PRMoureu
  • 12,817
  • 6
  • 38
  • 48
  • 1
    I think the way you used the 'zip( )' function is more effort saving in creating a custom template filter which is also another good approach for displaying the items in a list. Thank you so much it's really help me a lot. :) – TYL Oct 02 '17 at 05:07