如何在django模板中渲染有序字典? [英] How to render an ordered dictionary in django templates?
问题描述
我正在尝试学习django模板,但这并不容易。
我有一个特定的views.py包含一个用模板呈现的字典。字典由键值对组成,其中键是唯一的名称,值是与这些名称相关联的某些值。我以下列方式呈现字典:
I'm trying to learning django templates but it's not easy.
I have a certain views.py containing a dictionary to be rendered with a template. The dictionary is made of key-value pairs, where key are unique names and values are some values associated to those names. I render the dictionary in the following way:
return render_to_response('results.html', {'data': results_dict})
现在我的问题是,在我的模板中,我需要按字母顺序(或ASCIIbetical)顺序显示名称与亲戚的价值。
其实在我的模板我有:
Now my problem is that in my template I need to display the names in alphabetical (or ASCIIbetical) order with the relatives values.
Actually in my template I have:
<table>
{% for key, value in data.items %}
<tr>
<td> {{ key }}: </td> <td> {{ value }} </td>
</tr>
</table>
如何以排序的方式呈现数据?
非常感谢。
How can I render the data in sorted way? Many thanks.
推荐答案
在views.py(Python2)中:
In views.py (Python2):
return render_to_response('results.html',
{'data': sorted(results_dict.iteritems())})
或在views.py(Python3)中:
Or in views.py (Python3):
return render_to_response('results.html',
{'data': sorted(results_dict.items())})
在模板文件中:
{% for key, value in data %}
<tr>
<td> {{ key }}: </td> <td> {{ value }} </td>
</tr>
{% endfor %}
这篇关于如何在django模板中渲染有序字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!