make attrgetter take generic postprocess function
Before adoption: this commit came in with the history the project adopted, so no landing records it.
add changelog
authored by David Lord · committed by David Lord · parent f2fc06d · Browse files · 3 files·+39 added−24 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+39 added−24 removed
- tests:+9 added−9 removed
- other:+30 added−15 removed
Provenance
- Commit
bda4e6b- Tree
36c935f- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent
f2fc06d
3 files changed+39 added−24 removed
modified:jinja2/filters.py+28 added-15 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, lowercase=False):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.7 unmodified lines73 74 def attrgetter(item):75 for part in attribute:76 item = environment.getitem(item, part)71- if lowercase and isinstance(item, string_types):72- item = item.lower()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 @environmentfilter229-def do_sort(environment, value, reverse=False, case_sensitive=False,230- 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 """256- key_func = make_attrgetter(environment, attribute, not case_sensitive)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 @environmentfilter6 unmodified lines280 -> ['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 items271- from the iterable by themself instead and always returns a flat list of272- unique items. That can be useuful for example when you need to concatenate284+ 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 order281- as their first occurence in the iterable passed to the filter. If sorting294+ 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 """289- getter = make_attrgetter(environment, attribute, not case_sensitive)290-302+ getter = make_attrgetter(303+ environment, attribute,304+ postprocess=ignore_case if not case_sensitive else None305+ )306 seen = set()292- rv = []307 308 for item in value:309 key = getter(item)310+311 if key not in seen:312 seen.add(key)298- rv.append(item)313+ yield item314 300- return rv315 302-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 807 unmodified linesmodified:tests/test_filters.py+9 added-9 removed
389 unmodified lines390 def test_sort4(self, env):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_unique1(self, env):395- tmpl = env.from_string('{{ "".join(["b", "A", "a", "b"]|unique) }}')396- assert tmpl.render() == "bA"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_unique2(self, env):399- tmpl = env.from_string('{{ "".join(["b", "A", "a", "b"]|unique(true)) }}')400- assert tmpl.render() == "bAa"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_unique3(self, env):403- tmpl = env.from_string("{{ items|unique(attribute='value')|join }}")404- assert tmpl.render(items=map(Magic, [3, 2, 4, 1, 2])) == '3241'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},208 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