[英]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: 这是显示列表的display.html模板:
<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. 但运气不好,它不会根据索引'numbers'来显示结果,该索引假定为'0'到'3',而
td
标签保持为空。
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 : 更好的选择是在视图中创建一个
zip
对象,以将宠物与价格匹配,然后仅将其传递给模板:
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 : 然后可以将其解压缩到模板中,
zip()
会生成一个元组列表(name, price)
,您可以轻松地在其上循环:
<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 另一个解决方案是创建一个新的自定义模板过滤器 ,已经有一些帖子解释了此过程: https : //stackoverflow.com/a/29664945/6655211
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.