简体   繁体   English

循环以将Django视图上下文呈现为模板中的表格

[英]Loop to render Django view context as table in the template

I want to pass the following dictionary as context to Django template: 我想将以下字典作为上下文传递给Django模板:

context = {'prices': prices, 'listings_links': listings_links, 'listings_names': listings_names, 'photo_links': photo_links}

The dictionary's values are lists. 词典的值是列表。

In the template I want to display those lists as columns in HTML table. 在模板中,我想将这些列表显示为HTML表中的列。 However I am not sure how to further develop the following skeleton table code: 但是我不确定如何进一步开发以下框架表代码:

<table>
    <tr>
      <th>Price</th>
      <th>Link</th>
      <th>Listing name</th>
      <th>Photo link</th>
    </tr>
 {% for loop start here? %}
    <tr>
      <td> {{prices[0] }} </td>
      <td> {{ listings_links[0] }} </td>
      <td> {{ listings_names[0] }} </td>
      <td> {{ photo_links[0] }} </td>
    </tr>
    #next rows go here... 
 {% endfor %}
</table>

In the view, zip your lists into a single iterable. 在视图中,将列表压缩到一个可迭代的列表中。

items = zip(prices, listings_links, listings_names, photo_links)

context = {'items': item}

Then you can unpack items in the template: 然后,您可以解压缩模板中的items

{% for price, listing_link, listing_name, photo_link in items %}
  <tr>
    <td>{{ prices }}</td>
    <td>{{ listing_link }}</td>
    <td>{{ listing_name }}</td>
    <td>{{ photo_link }}</td>
  </tr>
{% endfor %}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM