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 key-value pairs, where key are unique names and values are some values associated to those names. I render the dictionary in the following way:
return render_to_response('results.html', {'data': results_dict})
Now my problem is that in my template I need to display the names in alphabetical (or ASCIIbetical) order with the relatives values.
Actually in my template I have:
<table> {% for key, value in data.items %} <tr> <td> {{ key }}: </td> <td> {{ value }} </td> </tr> </table>
How can I render the data in sorted way? Many thanks.
In views.py (Python2):
return render_to_response('results.html', {'data': sorted(results_dict.iteritems())})
Or in views.py (Python3):
return render_to_response('results.html', {'data': sorted(results_dict.items())})
In template file:
{% for key, value in data.items() %} <tr> <td> {{ key }}: </td> <td> {{ value }} </td> </tr> {% endfor %}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With