如何使用Jinja循环遍历对象数组、字典并将数据输出到表中?

2024-09-28 01:33:33 发布

您现在位置:Python中文网/ 问答频道 /正文

使用此格式的有效负载:

payload = (
 ('Franky hansen', '6 ',  '9', '12', 'prospekt'),
 ('Timmy hansen', '6 ',  '9', '12', 'not_interested'),
 ('Jhon hansen', '0 ',  '0', '0', 'Inactive')
     )

在带有要输出到的表的.Html文件中,我编写了以下jinja代码:

<table class="table table-striped ">
   <thead>
      <tr>
         {% for header in heads %}
         <th scope="col">{{ header.name }}</th>
         {% endfor %}
      </tr>
   </thead>
   <tbody>
      {% for deal in payload %}
      <tr>
         {% for data in deal %}
         <th scope="row">{{ data }}</th>
         {% endfor %}
      </tr>
      {% endfor %}
   </tbody>
</table>

我得到了表的正确输出:

enter image description here

但是,如果有效负载是这种格式,我如何循环并将正确的数据获取到正确的位置:

payload = 
 [
   {'name': 'Tom hansen'}, {'avg': '5 '}, {'num': '8'}, {'won': '11'},
   {'stat': 'customer'},
 
   {'name': 'Franky hansen'}, {'avg': '6 '}, {'num': '9'}, {'won': '12'},
   {'stat': 'prospekt'},
 
   {'name': 'Timmy hansen'}, {'avg': '7 '}, {'num': '10'}, {'won': '13'},
   {'stat': 'inactive'}
 ]

Tags: nameinfor格式tablenumtrstat
1条回答
网友
1楼 · 发布于 2024-09-28 01:33:33

你的问题只是“如何反复阅读字典”。下面是如何做到这一点

<table class="table table-striped ">
   <thead>
      <tr>
         {% for header in heads %}
         <th scope="col">{{ header.name }}</th>
         {% endfor %}
      </tr>
   </thead>
   <tbody>
      {% for deal in payload %}
      <tr>
         {% for key,data in deal.items() %}
         <th scope="row">{{ data }}</th>
         {% endfor %}
      </tr>
      {% endfor %}
   </tbody>
</table>

<table class="table table-striped ">
   <thead>
      <tr>
         {% for header in heads %}
         <th scope="col">{{ header.name }}</th>
         {% endfor %}
      </tr>
   </thead>
   <tbody>
      {% for deal in payload %}
      <tr>
         <th scope="row">{{ deal.get('name') }}</th>
         <th scope="row">{{ deal.get('avg') }}</th>
         <th scope="row">{{ deal.get('num') }}</th>
         <th scope="row">{{ deal.get('won') }}</th>
         <th scope="row">{{ deal.get('stat') }}</th>
      </tr>
      {% endfor %}
   </tbody>
</table>

相关问题 更多 >

    热门问题