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

 

  

 
       


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM