python之将数据以表格形式写入html

  背景:经过python工程处理之后,生成了一堆dict数据,通过render_template()将数据发送到html文件中,以table表格的形式显示。

  首先,我的dict数据只是单纯的key, value键值对。但是楼主只是初步接触过html的写法,所以,没有办法直接拆分键、值分别写入表格。

  所以,楼主先将键值对进行了处理:

       result_dict = {}  # 结果dict

    for key in dict:

      l_dict = {} #临时dict

      l_dict[ 'name' ] = key #键

      l_dict[ 'result' ] = dict[key] #值

      result_dict.append( l_dict )

   以上,将键、值分别对应上 name、result,接下来,是html中对数据的处理,通过

    render_template(" test.html ", result = result_dict) 将数据传入test.html,

   html处理数据:(只贴出body部分,设置了表格的部分样式)

<body>
Compare Result :
<style>
 table,table tr th, table tr td 
{ border:1px solid #ccc; } table{ width: 200px; border-collapse: collapse; } </style> <table border="1xp "> {% for foo in result %} <tr> <td>{{ foo["name"] }}</td> <td>{{ foo["result"] }}</td> </tr> {% endfor %} </table> </body>

  结果:

  

 

  其中对于dict数据的处理,是应用了jinja2中的{%%}和{{}}从html语法转义,详情见本博客https://www.cnblogs.com/weim-123/p/12964384.html

 

  


posted @ 2020-06-04 17:23  明朝乘扁舟  阅读(5904)  评论(0)    收藏  举报