1

下面是我用数据库中的数据创建的字典的打印结果。我试图在 html 中以日期顺序升序显示它。但是当我在模板中循环时,顺序不正确?我搜索并尝试了ordereddict,创建了一个自定义过滤器-->

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

没运气 !以下是我拥有的字典:

{u'Berplatform': {'days': {datetime.date(2012, 10, 31): {'': None},
                             datetime.date(2012, 11, 9): {<Event: Opening Coctail>: <Event: Opening Coctail>,
                                                          '': None},
                             datetime.date(2012, 11, 10): {'': None},
                             datetime.date(2012, 11, 11): {'': None},
                             datetime.date(2012, 11, 13): {'': None},
                             datetime.date(2012, 11, 17): {'': None},
                             datetime.date(2012, 11, 18): {'': None},
                             datetime.date(2012, 11, 24): {<Event: Platform is in Art İstanbul>: <Event: amberPlatform is in Art İstanbul>,
                                                           '': None},
                             datetime.date(2013, 7, 2): {<Event: ber12 exhibition 2>: <Event: amber12 exhibition 2>,
                                                         '': None}}},
4

1 回答 1

0

自定义模板标签是解决方案,但我在模板中使用错误。下面的用法是正确的。

自定义模板标签:

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

模板中的正确用法:

{% for venue, days in program.items %}
<div style='float:left; clear:both;'>
    <div class='boxRedBottom' style='width:100px;'>
        {{ venue }}
    </div>
    {% for key, values in days.items %}
        {% for key, events in values.items|sort %}  # Do the sorting of nested dict
            {% for event in events %}
                <div style='float:left; width:100px;  border:1px solid gray;'>
                {{ event }} {{ event.beginning_date }} 
                </div>
            {% endfor %}    
        {% endfor %}    
     {% endfor %}
</div>
{% endfor %}
于 2013-08-11T17:49:51.917 回答