如何在 Django 模板中呈现有序字典? [英] How to render an ordered dictionary in django templates?

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

问题描述

我正在尝试学习 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.items() %}
    <tr>
        <td> {{ key }}: </td> <td> {{ value }} </td>
    </tr>
{% endfor %}

这篇关于如何在 Django 模板中呈现有序字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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