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
Provenance
- Commit
4975ca0- Tree
7e5f1e7- Author
Sebastian Noack <sebastian.noack@gmail.com>- Committer
Sebastian Noack <sebastian.noack@gmail.com>- Parent
6bf78bc
2 files changed+77 added−26 removed
modified:jinja2/filters.py+56 added-19 removed
49 unmodified lines50 f.environmentfilter = True51 return f52 53 54-def make_attrgetter(environment, attribute):54+def 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]66+67 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 attrgetter74 75 177 unmodified lines253 254 .. 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)259 260 261+@environmentfilter262+def do_unique(environment, value, case_sensitive=False, attribute=None):263+ """Returns a list of unique items from the the given iterable.264+265+ .. sourcecode:: jinja266+267+ {{ ['foo', 'bar', 'foobar', 'FooBar']|unique }}268+ -> ['foo', 'bar', 'foobar']269+270+ 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:275+276+ .. sourcecode:: jinja277+278+ {{ ['foo', 'bar', 'foobar', 'FooBar']|unique|join(',') }}279+ -> foo,bar,foobar280+281+ 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:284+285+ .. sourcecode:: jinja286+287+ {{ ['foo', 'bar', 'foobar', 'FooBar']|unique|sort }}288+ -> ['bar', 'foo', 'foobar']289+ """290+ getter = make_attrgetter(environment, attribute, not case_sensitive)291+292+ seen = set()293+ rv = []294+295+ for item in value:296+ key = getter(item)297+ if key not in seen:298+ seen.add(key)299+ rv.append(item)300+301+ return rv302+303+304 def 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 lines1022 '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 linesmodified:tests/test_filters.py+21 added-7 removed
11 unmodified lines12 from jinja2 import Markup, Environment13 from jinja2._compat import text_type, implements_to_string14 15 16+@implements_to_string17+class Magic(object):18+ def __init__(self, value):19+ self.value = value20+21+ def __str__(self):22+ return text_type(self.value)23+24+25 @pytest.mark.filter26 class TestFilter():27 28 def test_filter_calling(self, env):327 unmodified lines356 tmpl = env.from_string('''{{ ['foo', 'Bar', 'blah']|sort }}''')357 assert tmpl.render() == "['Bar', 'blah', 'foo']"358 359 def test_sort4(self, env):351- @implements_to_string352- class Magic(object):353- def __init__(self, value):354- self.value = value355-356- 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'362 363+ def test_unique1(self, env):364+ tmpl = env.from_string('{{ "".join(["b", "A", "a", "b"]|unique) }}')365+ assert tmpl.render() == "bA"366+367+ def test_unique2(self, env):368+ tmpl = env.from_string('{{ "".join(["b", "A", "a", "b"]|unique(true)) }}')369+ assert tmpl.render() == "bAa"370+371+ 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'374+375 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