Present data from python dictionary to django template.?

☆樱花仙子☆ 提交于 2019-12-03 09:12:13

问题


I have a dictionary

data = {'sok': [ [1, 10] ], 'sao': [ [1, 10] ],'sok&sao':[ [2,20]] }

How Can I (Loop trough Dictionary ) present My data as (HTML) table to Django template.?? This format that as table

 author       qty            Amount
 sok            1              10         
 sao            1              10         
 sok&sao        2              20
 total               

回答1:


You can use the dict.items() method to get the dictionary elements:

<table>
    <tr>
        <td>author</td>
        <td>qty</td>
        <td>Amount</td>
    </tr>

    {% for author, values in data.items %}
    <tr>
        <td>{{author}}</td>
        {% for v in values.0 %}
        <td>{{v}}</td>
        {% endfor %}
    </tr>
    {% endfor %}
</table>



回答2:


Unfortunately, django templates do not deal with Python tuples. So it is not legal to use "for author, values" in the template. Instead, you must access tuple or array values by their index by using ".index", as in "tuple.0" and "tuple.1".

<table>
    <tr>
        <td>author</td>
        <td>qty</td>
        <td>Amount</td>
    </tr>

    {% for entry in data.items %}
    <tr>
        <td>{{entry.0}}</td>
        {% for v in entry.1 %}
        <td>{{v}}</td>
        {% endfor %}
    </tr>
    {% endfor %}
</table>



回答3:


In a project im working on now, i have had the same problem, thanks to your replies i've ended up doing something like this and it worked fine:

<table border=1 cellpadding=1 cellspacing=1>
<tr>
    <td>author</td>
    <td>qty</td>
    <td>Amount</td>
</tr>
{% for k,v in resultado.iteritems %}
    <tr><td> {{ k }} </td><td>{{ v[0] }}</td><td> {{ v[1] }} </td></tr>
{% endfor %}
</table>


来源:https://stackoverflow.com/questions/1541757/present-data-from-python-dictionary-to-django-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!