#15583: Sorting dict by keys within django template
-------------------------------------------------+-------------------------
Reporter: foxwhisper | Owner: nobody
Status: new | Milestone:
Component: Template system | Version: 1.2
Keywords: sort, dict, keys, template, | Triage Stage:
sorting, sorted, dictionary | Unreviewed
Has patch: 0 |
-------------------------------------------------+-------------------------
Currently, there is no way to sort a dict by its keys within a django
template without doing mods within the view. This really should just work
out of the box.
Test case:
{{{#!python
{'a': 'value 1',
'c': 'value 3',
'b': 'value 2',
}
{% for key, val in dict.items|sort %}
key: {{key}} / {{value}}
{% endfor %}
}}}
Current functionality:
{{{#!python
key: a / value 1
key: c / value 3
key: b / value 2
}}}
Functionality with sort patch:
{{{#!python
key: a / value 1
key: b / value 2
key: c / value 3
}}}
Someone has already written the appropriate code to do this (as a custom
filter), and seems to work fine. I'd like to see this taken up for
consideration to be put merged into the core, so you can use this filter
without needing to put it in via custom template tags.
Sadly, I haven't got time to write the necessary core changes, test it,
and submit as a patch file. If I get a chance before anyone else does,
I'll get this done.
{{{#!python
#File: custom_filters.py
# Author:
http://cookingupawebsiteindjango.blogspot.com/2009/05/custom-
template-filters-manipulating.html
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 = 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
}}}
--
Ticket URL: <http://code.djangoproject.com/ticket/15583>
Django <http://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.