incompatible change. The argument to the filter previously was the
optional starting index which defaultes to zero. This now became the
second argument to the function because it's rarely used.
+- like sum, sort now also makes it possible to order items by attribute.
Version 2.5.5
-------------
return sorted(value.items(), key=sort_func)
-def do_sort(value, reverse=False, case_sensitive=False):
+@environmentfilter
+def do_sort(environment, value, reverse=False, case_sensitive=False,
+ attribute=None):
"""Sort an iterable. Per default it sorts ascending, if you pass it
true as first argument it will reverse the sorting.
{% for item in iterable|sort %}
...
{% endfor %}
+
+ It is also possible to sort by an attribute (for example to sort
+ by the date of an object) by specifying the `attribute` parameter:
+
+ .. sourcecode:: jinja
+
+ {% for item in iterable|sort(attribute='date') %}
+ ...
+ {% endfor %}
+
+ .. versionchanged:: 2.6
+ The `attribute` parameter was added.
"""
if not case_sensitive:
def sort_func(item):
return item
else:
sort_func = None
+ if attribute is not None:
+ getter = make_attrgetter(environment, attribute)
+ def sort_func(item, processor=sort_func or (lambda x: x)):
+ return processor(getter(item))
return sorted(value, key=sort_func, reverse=reverse)
tmpl = env.from_string('''{{ ['foo', 'Bar', 'blah']|sort }}''')
assert tmpl.render() == "['Bar', 'blah', 'foo']"
+ def test_sort4(self):
+ class Magic(object):
+ def __init__(self, value):
+ self.value = value
+ def __unicode__(self):
+ return unicode(self.value)
+ tmpl = env.from_string('''{{ items|sort(attribute='value')|join }}''')
+ assert tmpl.render(items=map(Magic, [3, 2, 4, 1])) == '1234'
+
def test_groupby(self):
tmpl = env.from_string('''
{%- for grouper, list in [{'foo': 1, 'bar': 2},