johannix johannix - 2 years ago 425
Python Question

Django | sort dict in template

I want to print out a dictionary, sorted by the key. Sorting the keys is easy in the view, by just putting the keys in a list and then sorting the list. How can I loop through the keys in the template and then get the value from the dictionary.

{% for company in companies %}
{% for employee, dependents in %}
{% endfor %}
{% endfor %}

(Just made up the example...)
The part that doesn't work is the "" part. I need the "company" to be the value of company. Right now the company prat is looking for a key named "company" not the value of "company" from the loop above.

I'm doing a bit of processing to put the dictionary of dictionaries together. Changing the layout of the data isn't really an option. I figure the right approach is to write up a template tag, just wanted to know if there was a built-in way I missed.

Answer Source

try this:

a custom template filter will do the trick.

from django import template
register = template.Library()

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

    return value[arg]


more on custom template filters:

in your example you'd do:

{% for employee, dependents in company_dict|company %}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download