【发布时间】:2011-05-17 15:41:32
【问题描述】:
我有一本像 {'a':{'c':2, 'd':4 }, 'b': {'c':'value', 'd': 3}} 这样的字典
如何将其显示到视图中的表格中?
【问题讨论】:
-
递归自定义模板标签。
标签: python django django-templates django-views
我有一本像 {'a':{'c':2, 'd':4 }, 'b': {'c':'value', 'd': 3}} 这样的字典
如何将其显示到视图中的表格中?
【问题讨论】:
标签: python django django-templates django-views
问题已回答here:
总而言之,您可以像访问 python 字典一样访问代码
data = {'a': [ [1, 2] ], 'b': [ [3, 4] ],'c':[ [5,6]] }
您可以使用 dict.items() 方法获取字典元素:
<table>
<tr>
<td>a</td>
<td>b</td>
<td>c</td>
</tr>
{% for key, values in data.items %}
<tr>
<td>{{key}}</td>
{% for v in values[0] %}
<td>{{v}}</td>
{% endfor %}
</tr>
{% endfor %}
</table>
【讨论】:
取决于你想怎么做。在 Django 模板中,访问键的方式与访问方法的方式相同。也就是Python代码之类的
print my_dict['a']['c'] # Outputs: 2
变成
{{ my_dict.a.c }} {# Outputs: 2 #}
在 Django 模板中。
【讨论】:
dict 会产生键。
{% for key, item in my_dict.items %}。
遇到了类似的问题,我就这样解决了
Python
views.py
#I had a dictionary with the next structure
my_dict = {'a':{'k1':'v1'}, 'b':{'k2': 'v2'}, 'c':{'k3':'v3'}}
context = {'renderdict': my_dict}
return render(request, 'whatever.html', context)
HTML
{% for key, value in renderdict.items %}
<h1>{{ key }}</h1>
{% for k, v in value.items %}
<h1>{{ k }}</h1>
<h1 > {{ v }}</h1>
{% endfor %}
{% endfor %}
The outputs would be
{{ key }} = a
{{ k }} = k1
{{ v }} = v1 #and so forth through the loop.
【讨论】: