字典作为 Django 模板中的表格 [英] Dictionary As Table In Django Template

查看:32
本文介绍了字典作为 Django 模板中的表格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一本字典:

field = 

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

我的模板代码是:

<table width="100%" border="0">
     <tr>
        {% for k, v in field.items %}
            <th>{{ k }}</th>
        {% endfor %}
     </tr>
     <tr>
       {% for k,v in field.items %}
            <td>
                <table width="100%" border="0">
                 {% for a in v %}
                     <tr class="{% cycle 'odd' 'even' %}"><td>{{ a }}</td></tr>
                 {% endfor %}
                </table>
            </td>
        {% endfor %}
     </tr>
</table>

我想将字典键显示为表头,将 esach 值显示为行:

I want to show dictionary keys as table headers and esach value as row:

Birthday                          Education      Job        Child Sex
datetime.date(2012, 4, 6)         A1             job1       M
datetime.date(2012, 4, 27)        A2             job2       F

但我必须插入第二个表.有没有办法将字典键显示为表头,将 esach 值显示为行?

But I have to insert a second table. Is there any way toshow dictionary keys as table headers and esach value as rows?

提前致谢

推荐答案

如果您将数据作为字典中的表格提供,您可以使模板代码更易于阅读.它看起来更像这样:

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>

现在,您可以使用 field.keys() 获取 'headers' 值:

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

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

您可以使用以下循环获取 'values'(其中 2 是行数):

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)

或者作为单线:

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

这篇关于字典作为 Django 模板中的表格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆