Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Return only unique values in the output of the sort filter #443

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
16 changes: 14 additions & 2 deletions jinja2/filters.py
Expand Up @@ -224,7 +224,7 @@ def sort_func(item):

@environmentfilter
def do_sort(environment, value, reverse=False, case_sensitive=False,
attribute=None):
attribute=None, uniq=False):
"""Sort an iterable. Per default it sorts ascending, if you pass it
true as first argument it will reverse the sorting.

Expand All @@ -247,9 +247,18 @@ def do_sort(environment, value, reverse=False, case_sensitive=False,
...
{% endfor %}

When the `uniq` parameter is set to `true` duplicates will be removed
from the returned list.

.. versionchanged:: 2.6
The `attribute` parameter was added.

.. versionchanged:: 2.7.4
The `uniq` parameter was added.
"""
if uniq:
value_type = type(value)
value = set(value)
if not case_sensitive:
def sort_func(item):
if isinstance(item, string_types):
Expand All @@ -261,7 +270,10 @@ def sort_func(item):
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)
if uniq:
return value_type(sorted(value, key=sort_func, reverse=reverse))
else:
return sorted(value, key=sort_func, reverse=reverse)


def do_default(value, default_value=u'', boolean=False):
Expand Down