Merge pull request #735 from davidism/unique-filter
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Unique filter
authored by David Lord · committed by GitHub · parents ecba702, bda4e6b · Browse files · 3 files·+94 added−28 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
3 files+94 added−28 removed
- tests:+21 added−7 removed
- other:+73 added−21 removed
Provenance
- Commit
532171d- Tree
36c935f- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
ecba702- Parent 2
bda4e6b
3 files changed+94 added−28 removed
modified:jinja2/filters.py+71 added-21 removed
50 unmodified lines51 f.environmentfilter = True52 return f53 54 55+def ignore_case(value):56+ """For use as a postprocessor for :func:`make_attrgetter`. Converts strings57+ to lowercase and returns other types as-is."""58+ return value.lower() if isinstance(value, string_types) else value59+60+55-def make_attrgetter(environment, attribute):61+def make_attrgetter(environment, attribute, postprocess=None):62 """Returns a callable that looks up the given attribute from a63 passed object with the rules of the environment. Dots are allowed64 to access attributes of attributes. Integer parts in paths are65 looked up as integers.66 """61- if not isinstance(attribute, string_types) \62- or ('.' not in attribute and not attribute.isdigit()):63- return lambda x: environment.getitem(x, attribute)64- attribute = attribute.split('.')67+ if attribute is None:68+ attribute = []69+ elif isinstance(attribute, string_types):70+ attribute = [int(x) if x.isdigit() else x for x in attribute.split('.')]71+ else:72+ attribute = [attribute]73+74 def attrgetter(item):75 for part in attribute:67- if part.isdigit():68- part = int(part)76 item = environment.getitem(item, part)77+78+ if postprocess is not None:79+ item = postprocess(item)80+81 return item82+83 return attrgetter84 85 86 def do_forceescape(value):147 unmodified lines234 return sorted(value.items(), key=sort_func)235 236 237 @environmentfilter226-def do_sort(environment, value, reverse=False, case_sensitive=False,227- attribute=None):238+def do_sort(239+ environment, value, reverse=False, case_sensitive=False, attribute=None240+):241 """Sort an iterable. Per default it sorts ascending, if you pass it242 true as first argument it will reverse the sorting.243 244 If the iterable is made of strings the third parameter can be used to17 unmodified lines262 263 .. versionchanged:: 2.6264 The `attribute` parameter was added.265 """253- if not case_sensitive:254- def sort_func(item):255- if isinstance(item, string_types):256- item = item.lower()257- return item258- else:259- sort_func = None260- if attribute is not None:261- getter = make_attrgetter(environment, attribute)262- def sort_func(item, processor=sort_func or (lambda x: x)):263- return processor(getter(item))264- return sorted(value, key=sort_func, reverse=reverse)266+ key_func = make_attrgetter(267+ environment, attribute,268+ postprocess=ignore_case if not case_sensitive else None269+ )270+ return sorted(value, key=key_func, reverse=reverse)271 272 273+@environmentfilter274+def do_unique(environment, value, case_sensitive=False, attribute=None):275+ """Returns a list of unique items from the the given iterable.276+277+ .. sourcecode:: jinja278+279+ {{ ['foo', 'bar', 'foobar', 'FooBar']|unique }}280+ -> ['foo', 'bar', 'foobar']281+282+ This filter complements the `groupby` filter, which sorts and groups an283+ iterable by a certain attribute. The `unique` filter groups the items284+ from the iterable by themselves instead and always returns a flat list of285+ unique items. That can be useful for example when you need to concatenate286+ that items:287+288+ .. sourcecode:: jinja289+290+ {{ ['foo', 'bar', 'foobar', 'FooBar']|unique|join(',') }}291+ -> foo,bar,foobar292+293+ Also note that the resulting list contains the items in the same order294+ as their first occurrence in the iterable passed to the filter. If sorting295+ is needed you can still chain the `unique` and `sort` filter:296+297+ .. sourcecode:: jinja298+299+ {{ ['foo', 'bar', 'foobar', 'FooBar']|unique|sort }}300+ -> ['bar', 'foo', 'foobar']301+ """302+ getter = make_attrgetter(303+ environment, attribute,304+ postprocess=ignore_case if not case_sensitive else None305+ )306+ seen = set()307+308+ for item in value:309+ key = getter(item)310+311+ if key not in seen:312+ seen.add(key)313+ yield item314+315+316 def do_default(value, default_value=u'', boolean=False):317 """If the value is undefined it will return the passed default value,318 otherwise the value of the variable:319 794 unmodified lines1114 'sum': do_sum,1115 'title': do_title,1116 'trim': do_trim,1117 'truncate': do_truncate,1118+ 'unique': do_unique,1119 'upper': do_upper,1120 'urlencode': do_urlencode,1121 'urlize': do_urlize,1122 'wordcount': do_wordcount,4 unmodified linesmodified:tests/test_filters.py+21 added-7 removed
12 unmodified lines13 from jinja2 import Markup, Environment14 from jinja2._compat import text_type, implements_to_string15 16 17+@implements_to_string18+class Magic(object):19+ def __init__(self, value):20+ self.value = value21+22+ def __str__(self):23+ return text_type(self.value)24+25+26 @pytest.mark.filter27 class TestFilter(object):28 29 def test_filter_calling(self, env):357 unmodified lines387 tmpl = env.from_string('''{{ ['foo', 'Bar', 'blah']|sort }}''')388 assert tmpl.render() == "['Bar', 'blah', 'foo']"389 390 def test_sort4(self, env):382- @implements_to_string383- class Magic(object):384- def __init__(self, value):385- self.value = value386-387- def __str__(self):388- return text_type(self.value)391 tmpl = env.from_string('''{{ items|sort(attribute='value')|join }}''')392 assert tmpl.render(items=map(Magic, [3, 2, 4, 1])) == '1234'393 394+ def test_unique(self, env):395+ t = env.from_string('{{ "".join(["b", "A", "a", "b"]|unique) }}')396+ assert t.render() == "bA"397+398+ def test_unique_case_sensitive(self, env):399+ t = env.from_string('{{ "".join(["b", "A", "a", "b"]|unique(true)) }}')400+ assert t.render() == "bAa"401+402+ def test_unique_attribute(self, env):403+ t = env.from_string("{{ items|unique(attribute='value')|join }}")404+ assert t.render(items=map(Magic, [3, 2, 4, 1, 2])) == '3241'405+406 def test_groupby(self, env):407 tmpl = env.from_string('''408 {%- for grouper, list in [{'foo': 1, 'bar': 2},409 {'foo': 2, 'bar': 3},207 unmodified linesmodified:CHANGES+2 added
22 unmodified lines23 surrounding whitespace. Also added a new policy to enable this for all24 `trans` blocks.25 - The ``random`` filter is no longer incorrectly constant folded and will26 produce a new random choice each time the template is rendered. (`#478`_)27+- Add a ``unique`` filter. (`#469`_)28 29+.. _#469: https://github.com/pallets/jinja/pull/46930 .. _#478: https://github.com/pallets/jinja/pull/47831 32 Version 2.9.633 -------------505 unmodified lines