Django | 在模板中排序字典

joh*_*nix 8 python django

我想打印出一个字典,按键排序.通过将键放在列表中然后对列表进行排序,可以在视图中轻松地对键进行排序.如何循环模板中的键,然后从字典中获取值.

{% for company in companies %}
    {% for employee, dependents in company_dict.company.items %}
    {% endfor %}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)

(刚刚编写的例子......)不起作用的部分是"company_dict.company.items"部分.我需要"公司"才能成为公司的价值所在.现在,公司的Prat正在寻找一个名为"公司"的钥匙,而不是上面循环中"公司"的价值.

我正在做一些处理,把字典词典放在一起.改变数据的布局实际上不是一种选择.我认为正确的方法是编写模板标签,只是想知道我是否有错过的内置方式.

小智 19

创建自定义过滤器,如下所示:

from django import template
from django.utils.datastructures import SortedDict

register = template.Library()

@register.filter(name='sort')
def listsort(value):
    if isinstance(value, dict):
        new_dict = SortedDict()
        key_list = sorted(value.keys())
        for key in key_list:
            new_dict[key] = value[key]
        return new_dict
    elif isinstance(value, list):
        return sorted(value)
    else:
        return value
    listsort.is_safe = True
Run Code Online (Sandbox Code Playgroud)

然后在你的模板中你应该使用:

{% for key, value in companies.items|sort %}
      {{ key }} {{ value }}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)

您将能够通过Key获取已排序的词典.


Bra*_*nry 3

自定义模板过滤器就可以解决问题。

from django import template
register = template.Library()

def dict_get(value, arg):
    #custom template tag used like so:
    #{{dictionary|dict_get:var}}
    #where dictionary is duh a dictionary and var is a variable representing
    #one of it's keys

    return value[arg]

register.filter('dict_get',dict_get)
Run Code Online (Sandbox Code Playgroud)

有关自定义模板过滤器的更多信息:http://docs.djangoproject.com/en/dev/howto/custom-template-tags/#howto-custom-template-tags

在你的例子中你会这样做:

{% for employee, dependents in company_dict|company %}
Run Code Online (Sandbox Code Playgroud)

  • 多谢!我必须稍微修改一下你所做的事情。我的过滤器返回“value[arg].iteritems()”,模板如下所示: {% for employee, dependents in company_dict|get_dict_and_iter:company %} (2认同)