首页 > 解决方案 > Django:字典到 HTML 表,当值是生成器时

问题描述

我有一本包含抓取的 Airbnb 列表数据的字典:

all_data = {
                    'name' : self.detail('listing', 'name'),
                    'city' : self.detail('listing', 'city'),
                    'id' : self.detail('listing', 'id'),
                    'latitude' : self.detail('listing', 'lat'),
                    'longitude' : self.detail('listing', 'lng'),
                    'picture' : self.detail('listing', 'picture_url'),
                    'pictures' : self.detail('listing', 'picture_urls'),
                    'price' : self.detail('pricing_quote', 'rate', 'amount'),
                    'currency' : self.detail('pricing_quote', 'rate', 'currency')
                    }

我从 Django 视图传递到这样的模板:

context = {'all_data':all_data}
return render(request, 'javascript/testjson.html', context)

此字典中的值是生成器,产生特定的列表详细信息。

如何在模板中以 HTML 表格形式呈现这些数据?

到目前为止,我有以下显示标题,但我不知道如何将生成器中的数据提取到这些标题下方的列中:

<table>
    <tr>
        {% for key, value in all_data.items %}
            <th>{{key}}</th>
        {% endfor %}
    </tr>
</table>

标签: pythonhtmldjango

解决方案


你可以像这样更新html

<table>
  <tr>
    {% for key in all_data.keys %}
        <th>{{key}}</th>
    {% endfor %}
  </tr>
  <tr>
    {% for value in all_data.values %}
        <td>
         {% for v in value %}
           {{v}}
         {% endfor %
       </td>
    {% endfor %}
  </tr>
</table>

这将工作....


推荐阅读