背景:经过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