http://docs.djangoproject.com/en/dev/ref/templates/builtins/#regroup
I can think of a few ways of doing it with loops but I'd particularly like to know if there is a neat one-liner.
Django Code The template tags are a way of telling Django that here comes something else than plain HTML. The template tags allows us to to do some programming on the server before sending HTML to the client. In the next chapters you will learn about the most common template tags.
{% %} and {{ }} are part of Django templating language. They are used to pass the variables from views to template. {% %} is basically used when you have an expression and are called tags while {{ }} is used to simply access the variable.
Django Template Tags are simple Python functions which accepts a 1 or more value, an optional argument, process those values and return a value to be displayed on the page. First, In your application folder, create a "templatetags" directory at the same level as the models and views.
spaceless. Removes whitespace between HTML tags. This includes tab characters and newlines.
Combine itertools.groupby
with operator.itemgetter
to get a pretty nice solution:
from operator import itemgetter
from itertools import groupby
key = itemgetter('gender')
iter = groupby(sorted(people, key=key), key=key)
for gender, people in iter:
print '===', gender, '==='
for person in people:
print person
If the source of data (people
in this case) is already sorted by the key, you can bypass the sorted
call:
iter = groupby(people, key=lambda x:x['gender'])
for gender, people in iter:
print '===', gender, '==='
for person in people:
print person
Note: If sorted
is a common dictionary, there are no guarantees of order; therefore you must call sorted
. Here I'm supposing that sorted
is a collections.OrderedDict
or some other kind of ordered data structure.
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