Skip to content
Myr

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

3 files+94 added−28 removed

modified:jinja2/filters.py+71 added-21 removed
50 unmodified lines
51 f.environmentfilter = True52 return f535455def 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 value596055def make_attrgetter(environment, attribute):61def 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]7374 def attrgetter(item):75 for part in attribute:67 if part.isdigit():68 part = int(part)76 item = environment.getitem(item, part)7778 if postprocess is not None:79 item = postprocess(item)8081 return item8283 return attrgetter848586def do_forceescape(value):
147 unmodified lines
234 return sorted(value.items(), key=sort_func)235236237@environmentfilter226def do_sort(environment, value, reverse=False, case_sensitive=False,227 attribute=None):238def 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.243244 If the iterable is made of strings the third parameter can be used to
17 unmodified lines
262263 .. 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)271272273@environmentfilter274def do_unique(environment, value, case_sensitive=False, attribute=None):275 """Returns a list of unique items from the the given iterable.276277 .. sourcecode:: jinja278279 {{ ['foo', 'bar', 'foobar', 'FooBar']|unique }}280 -> ['foo', 'bar', 'foobar']281282 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:287288 .. sourcecode:: jinja289290 {{ ['foo', 'bar', 'foobar', 'FooBar']|unique|join(',') }}291 -> foo,bar,foobar292293 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:296297 .. sourcecode:: jinja298299 {{ ['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()307308 for item in value:309 key = getter(item)310311 if key not in seen:312 seen.add(key)313 yield item314315316def 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 lines
1114 '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 lines
modified:tests/test_filters.py+21 added-7 removed
12 unmodified lines
13from jinja2 import Markup, Environment14from jinja2._compat import text_type, implements_to_string151617@implements_to_string18class Magic(object):19 def __init__(self, value):20 self.value = value2122 def __str__(self):23 return text_type(self.value)242526@pytest.mark.filter27class TestFilter(object):2829 def test_filter_calling(self, env):
357 unmodified lines
387 tmpl = env.from_string('''{{ ['foo', 'Bar', 'blah']|sort }}''')388 assert tmpl.render() == "['Bar', 'blah', 'foo']"389390 def test_sort4(self, env):382 @implements_to_string383 class Magic(object):384 def __init__(self, value):385 self.value = value386387 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'393394 def test_unique(self, env):395 t = env.from_string('{{ "".join(["b", "A", "a", "b"]|unique) }}')396 assert t.render() == "bA"397398 def test_unique_case_sensitive(self, env):399 t = env.from_string('{{ "".join(["b", "A", "a", "b"]|unique(true)) }}')400 assert t.render() == "bAa"401402 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'405406 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 lines
modified:CHANGES+2 added
22 unmodified lines
23 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`_)2829.. _#469: https://github.com/pallets/jinja/pull/46930.. _#478: https://github.com/pallets/jinja/pull/4783132Version 2.9.633-------------
505 unmodified lines