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 %}
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 %}
...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.