[英]Dictionary As Table In Django Template
I have a dictionary:我有一本字典:
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']
}
My template code is:我的模板代码是:
<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>
I want to show dictionary keys as table headers and esach value as row:我想将字典键显示为表头,将 esach 值显示为行:
Birthday Education Job Child Sex
datetime.date(2012, 4, 6) A1 job1 M
datetime.date(2012, 4, 27) A2 job2 F
But I have to insert a second table.但我必须插入第二张表。 Is there any way toshow dictionary keys as table headers and esach value as rows?
有什么方法可以将字典键显示为表头,将 esach 值显示为行?
Thanks in advance提前致谢
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()
:现在,您可以使用
field.keys()
获取'headers'
值:
[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):您可以使用以下循环获取
'values'
(其中2
是行数):
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: Simeon 的回答对我有用,但由于嵌套列表,我不得不在模板中做一些不同的事情以使行和数据看起来正确:
{% for row in field.rows %}
<tr>
{% for value in row %}
<td>{{value}}</td>
{% endfor %}
</tr>
{% endfor %}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.