Dictionary As Table In Django Template

戏子无情 提交于 2019-12-01 20:52:12

You can make the template code a lot easier to read if you provide the data as a table in your dictionary. It would look more like this:

field = {
    'headers': [u'Birthday:', u'Education', u'Job', u'Child Sex'],
    'rows': [[datetime.date(2012, 4, 6), u'A1', u'job1', u'M']
            ,[datetime.date(2012, 4, 27), u'A2', u'job2', u'F']]
}

You can now iterate over the headers as follows:

<tr>
{% for header in field.headers %}
    <th>{{ header }}</th>
{% endfor %}
</tr>

And each row can be displayed using:

<tr>    
{% for value in field.rows %}
    <td>{{ value }}</td>
{% endfor %}
</tr>

Now, you can obtain the 'headers' value using field.keys():

[u'Birthday:', u'Education', u'Job:', u'Child Sex:']

You can get the 'values' using the following loop (where 2 is the number of rows):

rows = []
for i in xrange(2):
    row = []
    for k in field.keys():
        row.append(field[k][i])
    rows.append(row)

Or as a one-liner:

rows = [[field[k][i] for k in field.keys()] for i in xrange(2)]

Simeon's answer worked for me, but I had to do something a little different int the template to get the rows and data looking right because of the nested list:

        {% for row in field.rows %}
            <tr>
                {% for value in row %}
                    <td>{{value}}</td>
                {% endfor %}
            </tr>
        {% endfor %}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!