0

I have 4 lists with the same length and would like to pass all of them to the html page.

views.py

return render(request, 'result.html', {'listA':listA, 'listB':listB,  'listC':listC, 'listD':listD})

And here is the code when I tried with Flask.

app.py

return render_template('result.html', listA = listA, listB = listB, listC = listC, listD = listD)

Below is the code in the template file; with Flask, it prints out the table without any problems, but it doesn't seem to work with Django. How should I fix my code?

result.html

{% for i in listA %}
<tr>
<th> {{ listA[loop.index] }} </th>
<td> {{ listB[loop.index] }} </td>
<td> {{ listC[loop.index] }} </td>
<td> {{ listD[loop.index] }} </td>
</tr>
{% endfor %}
davidism
  • 121,510
  • 29
  • 395
  • 339
Tsao
  • 139
  • 1
  • 10
  • What error do you get ? Please post your traceback. – 0decimal0 Aug 27 '17 at 08:28
  • 1
    Possible duplicate of [Get list item dynamically in django templates](https://stackoverflow.com/questions/8948430/get-list-item-dynamically-in-django-templates) – Brown Bear Aug 27 '17 at 08:30
  • Here's the error I got: Could not parse the remainder: '[loop.index]' from 'listA[loop.index]' – Tsao Aug 27 '17 at 08:57

1 Answers1

0

You should use a custom templatetag for implementing lookup, because django does not provide one for you. and then use django template engine for loop for getting forloop.counter0

First create templatetags directory with __init__.py inside your app folder. Lets assume your app is called polls folder structure will look like this:

polls/
    __init__.py
    models.py
    templatetags/
        __init__.py
        lookup.py
    views.py

After write lookup code which goes inside lookup.py:

from django import template

register = template.Library()

@register.filter
def lookup(d, key):
    return d[key]

And finlly use it in template file:

{% load lookup %}
...
{% for i in listA %}
    <tr>
        <th> {{ listA|lookup:forloop.counter0 }} </th>
        <td> {{ listB|lookup:forloop.counter0 }}</td>
        <td> {{ listC|lookup:forloop.counter0 }}</td>
        <td> {{ listD|lookup:forloop.counter0 }}</td>
    </tr>
{%  endfor %}
...
demonno
  • 524
  • 5
  • 14
  • i think this question is duplicate of (get-list-item)[https://stackoverflow.com/questions/8948430/get-list-item-dynamically-in-django-templates] – Brown Bear Aug 27 '17 at 08:59
  • I got an error of " Invalid filter: 'lookup' " I'll read the django documentation first thank you! – Tsao Aug 27 '17 at 09:04
  • @Tsao check out Ref 2, seems a problem of registering `lookup` template tag. – demonno Aug 27 '17 at 09:07
  • @demonno So I added 'builtins': [ '[[projectname]].filter.lookup',], to my TEMPLATES but there's an error : "Invalid template library specified." – Tsao Aug 27 '17 at 09:16
  • @Tsao see proper location for template tag `lookup` code in the updated answer. – demonno Aug 27 '17 at 09:32