Python字典在flas中转换为HTML

2024-04-26 09:31:54 发布

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

我有python字典,里面有一个字典列表。我试图把这个转换成一个HTML表,我可以给Flask render_模板

我的字典格式是:

{'sentiment_analysis_result': [{'article_title': u'These Digital Locks Help Keep Tabs on Tenants', 'score': u'0.139613', 'type': u'positive'}, {'article_title': u'You Can Get a $50 Phone From Amazon, If You Don\u2019t Mind the Ads', 'score': u'0.239663', 'type': u'positive'}]}

我希望键是title,值是values。任何帮助都会很感激的!在

在尝试@EliasMP的答案后,表格的格式是:

enter image description here


Tags: you模板flask列表字典titlehtml格式
2条回答

只需将字典从控制器传递到模板并循环两次。第一个用于恢复dictionary的每个元素(分别为key和value),第二个用于恢复每个列表中的每个元素(之前恢复的值),使用html绘制它们(table tag,div格式为table是正确的方式,table的tag正在过时)

<table>
    <tr>
        <th>name_of_list</th>
        <th>values</th>
    </tr>

    {% for key, values in your_dictionary.items() %}
    <tr>
        <td>{{key}}</td>
        <td>
        <table>
           <tr>
             <th>article_title</th>
             <th>score</th>
             <th>type</th>
           </tr>
           <tr>
           {% for articles in values %}
               <td>{{article.article_title}}</td>
               <td>{{article.score}}</td>
               <td>{{article.type}}</td>
           {% endfor %}
           </tr>
        </td>
     </tr>
    {% endfor %}

</table>

这不是最有效的方法,但是如果您想将已经呈现为html的表作为变量传递给视图,则可以完成任务。更好的方法是只传递数据,然后让模板使用模板逻辑循环并在您想要的位置输出变量。在

data = {'sentiment_analysis_result': [{'article_title': u'These Digital Locks Help Keep Tabs on Tenants', 'score': u'0.139613', 'type': u'positive'}, {'article_title': u'You Can Get a $50 Phone From Amazon, If You Don\u2019t Mind the Ads', 'score': u'0.239663', 'type': u'positive'}]}

table_string = '<table>'
for key, value in data.iteritems():
    table_string += '<thead>'
    table_string += '<th>' + key + '</th>'
    table_string += '</thead>'
    table_string += '<tbody>'
    for i, d in enumerate(value):
        if i == 0:
            table_string += '<tr>'
            for k in d.iterkeys():
                table_string += '<td>' + k + '</td>'
            table_string += '</tr>'
        table_string += '<tr>'
        for v in d.itervalues():
            table_string += '<td>' + v + '</td>'
        table_string += '</tr>'
    table_string += '</tbody>'
table_string += '</table>'

print(table_string)

相关问题 更多 >