简体   繁体   English

Python / Django - 如何将字典中的值列表 map 转换为 HTML 表?

[英]Python / Django - How to map a list of values in a dictionary to a HTML table?

My Django View:我的 Django 查看:

def hub(request):

  context = {} 

  hub_id = [value['id'] for value in hub_data['data']]
  hub_name = [value['attributes']['name'] for value in hub_data['data']]
  hub_url = [value['links']['self']['href'] for value in hub_data['data']]

  nested_dict = dict(zip(hub_name, map(list, zip(hub_id, hub_url))))

  context ['rows'] = nested_dict

  return render(request, 'connector/hub.html', context)

The context['rows'] results in: context['rows'] 导致:

{'rows': {hub_name1 : ['hub_id1', 'hub_url1'],{hub_name2 : ['hub_id2', 'hub_url2'], etc.. }

I am trying to pass it a HTML table that looks like this:我正在尝试将 HTML 表传递给它,如下所示:

  <th scope="col">Hub Name</th>
  <th scope="col">Hub ID</th>
  <th scope="col">Hub URL</th>

My tablebody looks like this:我的桌身看起来像这样:

  <tbody>
    {% for key, value in rows.items %}
      <tr>
        <td> {{ key }}</td>
        <td> {{ value }}</td> **//how do i just get hub_id here**
        <td> Don't know what to do here to get: hub_url </td>

      </tr>  
    {% endfor %}
  </tbody>

But I want to add another -tag to fill with hub_url.但我想添加另一个 -tag 来填充 hub_url。 How do I extract the hub_id data and add it to the column: Hub ID and extract the hub_url and add it to the column Hub URL.如何提取 hub_id 数据并将其添加到列:Hub ID 并提取 hub_url 并将其添加到列 Hub URL。

Any help would be much appreciated!任何帮助将非常感激!

You can pass the data to the template without transforming it您可以将数据传递给模板而无需对其进行转换

return render(request, 'connector/hub.html', {'data': hub_data['data']})

And then lookup the attributes using the "dot" template syntax for each row然后使用每一行的“点”模板语法查找属性

<tbody>
  {% for row in data %}
    <tr>
      <td>{{ row.attributes.name }}</td>
      <td>{{ row.id }}</td>
      <td>{{ row.links.self.href }}</td>
    </tr>  
  {% endfor %}
</tbody>

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

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