【问题标题】:How do I return a Python bottle template that prints out key-value pairs from a dictionary?如何返回从字典中打印出键值对的 Python 瓶子模板?
【发布时间】:2014-12-06 20:19:18
【问题描述】:

目的是从字典中提取数据,并以表格的形式返回键值对 这是我的 Python 代码部分:

dictionary = dict()
dictionary = {'hello': 1, 'hi': 2, 'go': 3}
output = template('make_table', wordList=dictionary)
return output

这是我的 make_table.tpl 文件的一部分:

<table>
%for index in wordList:
    <tr>
        <td>{{index}} </td>
    </tr>
%end
</table>

不幸的是,tpl 文件只显示键:“hello”、“hi”和“go”,但没有显示它们的值。

我想要的是能够显示:

你好 1 嗨 2 去 3

谁能告诉我如何在 tpl 文件中索引值?

【问题讨论】:

    标签: python dictionary html-table bottle


    【解决方案1】:

    您可以使用iteritems() 遍历模板中的字典项:

    <table>
    %for key, value in wordList.iteritems():
        <tr>
            <td>{{key}} </td>
            <td>{{value}} </td>
        </tr>
    %end
    </table>
    

    演示:

    >>> from bottle import template
    >>> t = """
    ... <table>
    ... %for key, value in wordList.iteritems():
    ...     <tr>
    ...         <td>{{key}} </td>
    ...         <td>{{value}} </td>
    ...     </tr>
    ... %end
    ... </table>
    ... """
    >>> print template(t, wordList={'hello': 1, 'hi': 2, 'go': 3})
    <table>
        <tr>
            <td>go </td>
            <td>3 </td>
        </tr>
        <tr>
            <td>hi </td>
            <td>2 </td>
        </tr>
        <tr>
            <td>hello </td>
            <td>1 </td>
        </tr>
    </table>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-12-26
      • 1970-01-01
      • 1970-01-01
      • 2019-05-22
      • 1970-01-01
      • 1970-01-01
      • 2013-03-24
      • 2017-07-19
      相关资源
      最近更新 更多