Skip to content
Myr

Added unique filter

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Sebastian Noack · committed by Sebastian Noack · parent 6bf78bc · Browse files · 2 files+77 added−26 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

2 files+77 added−26 removed

  • tests:+21 added−7 removed
  • other:+56 added−19 removed

2 files+77 added−26 removed

modified:jinja2/filters.py+56 added-19 removed
49 unmodified lines
50 f.environmentfilter = True51 return f525354def make_attrgetter(environment, attribute):54def make_attrgetter(environment, attribute, lowercase=False):55 """Returns a callable that looks up the given attribute from a56 passed object with the rules of the environment. Dots are allowed57 to access attributes of attributes. Integer parts in paths are58 looked up as integers.59 """60 if not isinstance(attribute, string_types) \61 or ('.' not in attribute and not attribute.isdigit()):62 return lambda x: environment.getitem(x, attribute)63 attribute = attribute.split('.')60 if attribute is None:61 attribute = []62 elif isinstance(attribute, string_types):63 attribute = [int(x) if x.isdigit() else x for x in attribute.split('.')]64 else:65 attribute = [attribute]6667 def attrgetter(item):68 for part in attribute:66 if part.isdigit():67 part = int(part)69 item = environment.getitem(item, part)70 if lowercase and isinstance(item, string_types):71 item = item.lower()72 return item73 return attrgetter7475
177 unmodified lines
253254 .. versionchanged:: 2.6255 The `attribute` parameter was added.256 """254 if not case_sensitive:255 def sort_func(item):256 if isinstance(item, string_types):257 item = item.lower()258 return item259 else:260 sort_func = None261 if attribute is not None:262 getter = make_attrgetter(environment, attribute)263 def sort_func(item, processor=sort_func or (lambda x: x)):264 return processor(getter(item))265 return sorted(value, key=sort_func, reverse=reverse)257 key_func = make_attrgetter(environment, attribute, not case_sensitive)258 return sorted(value, key=key_func, reverse=reverse)259260261@environmentfilter262def do_unique(environment, value, case_sensitive=False, attribute=None):263 """Returns a list of unique items from the the given iterable.264265 .. sourcecode:: jinja266267 {{ ['foo', 'bar', 'foobar', 'FooBar']|unique }}268 -> ['foo', 'bar', 'foobar']269270 This filter complements the `groupby` filter, which sorts and groups an271 iterable by a certain attribute. The `unique` filter groups the items272 from the iterable by themself instead and always returns a flat list of273 unique items. That can be useuful for example when you need to concatenate274 that items:275276 .. sourcecode:: jinja277278 {{ ['foo', 'bar', 'foobar', 'FooBar']|unique|join(',') }}279 -> foo,bar,foobar280281 Also note that the resulting list contains the items in the same order282 as their first occurence in the iterable passed to the filter. If sorting283 is needed you can still chain the `unique` and `sort` filter:284285 .. sourcecode:: jinja286287 {{ ['foo', 'bar', 'foobar', 'FooBar']|unique|sort }}288 -> ['bar', 'foo', 'foobar']289 """290 getter = make_attrgetter(environment, attribute, not case_sensitive)291292 seen = set()293 rv = []294295 for item in value:296 key = getter(item)297 if key not in seen:298 seen.add(key)299 rv.append(item)300301 return rv302303304def do_default(value, default_value=u'', boolean=False):305 """If the value is undefined it will return the passed default value,306 otherwise the value of the variable:307
714 unmodified lines
1022 'sum': do_sum,1023 'title': do_title,1024 'trim': do_trim,1025 'truncate': do_truncate,1026 'unique': do_unique,1027 'upper': do_upper,1028 'urlencode': do_urlencode,1029 'urlize': do_urlize,1030 'wordcount': do_wordcount,
3 unmodified lines
modified:tests/test_filters.py+21 added-7 removed
11 unmodified lines
12from jinja2 import Markup, Environment13from jinja2._compat import text_type, implements_to_string141516@implements_to_string17class Magic(object):18 def __init__(self, value):19 self.value = value2021 def __str__(self):22 return text_type(self.value)232425@pytest.mark.filter26class TestFilter():2728 def test_filter_calling(self, env):
327 unmodified lines
356 tmpl = env.from_string('''{{ ['foo', 'Bar', 'blah']|sort }}''')357 assert tmpl.render() == "['Bar', 'blah', 'foo']"358359 def test_sort4(self, env):351 @implements_to_string352 class Magic(object):353 def __init__(self, value):354 self.value = value355356 def __str__(self):357 return text_type(self.value)360 tmpl = env.from_string('''{{ items|sort(attribute='value')|join }}''')361 assert tmpl.render(items=map(Magic, [3, 2, 4, 1])) == '1234'362363 def test_unique1(self, env):364 tmpl = env.from_string('{{ "".join(["b", "A", "a", "b"]|unique) }}')365 assert tmpl.render() == "bA"366367 def test_unique2(self, env):368 tmpl = env.from_string('{{ "".join(["b", "A", "a", "b"]|unique(true)) }}')369 assert tmpl.render() == "bAa"370371 def test_unique3(self, env):372 tmpl = env.from_string("{{ items|unique(attribute='value')|join }}")373 assert tmpl.render(items=map(Magic, [3, 2, 4, 1, 2])) == '3241'374375 def test_groupby(self, env):376 tmpl = env.from_string('''377 {%- for grouper, list in [{'foo': 1, 'bar': 2},378 {'foo': 2, 'bar': 3},
194 unmodified lines