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

标签 python django jinja2

我正在尝试显示两个列表中的项目。这是我的代码:

#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})

这是显示列表的 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>

但不幸的是,它不会根据索引“numbers”显示结果,索引“numbers”假定为从“0”到“3”,td 标记仍为空。

最佳答案

更好的选择是创建 zip您 View 中的对象,将宠物与价格相匹配,然后仅将其传递给模板:

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})

然后您可以在模板中将其解压,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>

另一个解决方案是创建一个新的自定义 template filter ,已经有一些帖子解释了这个过程:https://stackoverflow.com/a/29664945/6655211

关于python - Django /Jinja2 : How to use the index value in a for-loop statement to display two lists?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46517303/

相关文章:

python - 一次性字典?

python - NumPy 中的一维数组

django - 在Django的自定义404/500页面中使用静态文件

python - Flask 的静态 Assets 在推送到 Elastic Beanstalk 时返回 404 错误

Python/Tkinter : Are Tkinter StringVar (IntVar, 等)线程安全吗?

Python:如何查找/检查函数接受什么类型的参数?

django - (django) 整个项目的静态文件

javascript - 在 django 中接收嵌套的 JSON 对象

jquery - 有什么方法可以使用jinja2和flask形式而不是ajax和jquery或两者都使用?

python-3.x - Jinja2 中的独特列表过滤器