How to render an ordered dictionary in django templates?

后端 未结 4 373
情书的邮戳
情书的邮戳 2021-01-31 14:58

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 ke

4条回答
  •  再見小時候
    2021-01-31 16:00

    Another solution that worked very well for me and I think it's simplier. It uses OrderedDict() more info

    In your views.py file add:

    from collections import OrderedDict
    def main(request):
        ord_dict = OrderedDict()
        ord_dict['2015-06-20'] = {}
        ord_dict['2015-06-20']['a'] = '1'
        ord_dict['2015-06-20']['b'] = '2'
        ord_dict['2015-06-21'] = {}
        ord_dict['2015-06-21']['a'] = '10'
        ord_dict['2015-06-21']['b'] = '20'
        return render(request, 'main.html', {'context': ord_dict})
    

    Then in your template, you can do:

    
    {% for key, value in context.items %}
        
    {% endfor %}
    
    {{ key }} {{ value.a }} {{ value.b }}

    This will return the keys of the dictionary in the same ordered that they were put in.

    2015-06-20  1   2
    2015-06-21  10  20
    

提交回复
热议问题