Skip to content
Myr

Merge pull request #737 from davidism/minmax-filters

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

min and max filters

authored by David Lord · committed by GitHub · parents 532171d, 52dcb47 · Browse files · 3 files+74 added−19 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+74 added−19 removed

  • tests:+20 added−0 removed
  • other:+54 added−19 removed

3 files+74 added−19 removed

modified:jinja2/filters.py+52 added-19 removed
10 unmodified lines
11import re12import math13import random1415from itertools import groupby15from itertools import groupby, chain16from collections import namedtuple17from jinja2.utils import Markup, escape, pformat, urlize, soft_unicode, \18 unicode_urlencode, htmlsafe_json_dumps19from jinja2.runtime import Undefined
258 unmodified lines
278279 {{ ['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:282 The unique items are yielded in the same order as their first occurrence in283 the iterable passed to the filter.284288 .. 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']285 :param case_sensitive: Treat upper and lower case strings as distinct.286 :param attribute: Filter objects with unique values for this attribute.287 """288 getter = make_attrgetter(289 environment, attribute,290 postprocess=ignore_case if not case_sensitive else None
7 unmodified lines
298 seen.add(key)299 yield item300301302def _min_or_max(environment, value, func, case_sensitive, attribute):303 it = iter(value)304305 try:306 first = next(it)307 except StopIteration:308 return environment.undefined('No aggregated item, sequence was empty.')309310 key_func = make_attrgetter(311 environment, attribute,312 ignore_case if not case_sensitive else None313 )314 return func(chain([first], it), key=key_func)315316317@environmentfilter318def do_min(environment, value, case_sensitive=False, attribute=None):319 """Return the smallest item from the sequence.320321 .. sourcecode:: jinja322323 {{ [1, 2, 3]|min }}324 -> 1325326 :param case_sensitive: Treat upper and lower case strings as distinct.327 :param attribute: Get the object with the max value of this attribute.328 """329 return _min_or_max(environment, value, min, case_sensitive, attribute)330331332@environmentfilter333def do_max(environment, value, case_sensitive=False, attribute=None):334 """Return the smallest item from the sequence.335336 .. sourcecode:: jinja337338 {{ [1, 2, 3]|max }}339 -> 3340341 :param case_sensitive: Treat upper and lower case strings as distinct.342 :param attribute: Get the object with the max value of this attribute.343 """344 return _min_or_max(environment, value, max, case_sensitive, attribute)345346347def do_default(value, default_value=u'', boolean=False):348 """If the value is undefined it will return the passed default value,349 otherwise the value of the variable:350
776 unmodified lines
1127 'length': len,1128 'list': do_list,1129 'lower': do_lower,1130 'map': do_map,1131 'min': do_min,1132 'max': do_max,1133 'pprint': do_pprint,1134 'random': do_random,1135 'reject': do_reject,1136 'rejectattr': do_rejectattr,
23 unmodified lines
modified:tests/test_filters.py+20 added
401 unmodified lines
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'405406 @pytest.mark.parametrize('source,expect', (407 ('{{ ["a", "B"]|min }}', 'a'),408 ('{{ ["a", "B"]|min(case_sensitive=true) }}', 'B'),409 ('{{ []|min }}', ''),410 ('{{ ["a", "B"]|max }}', 'B'),411 ('{{ ["a", "B"]|max(case_sensitive=true) }}', 'a'),412 ('{{ []|max }}', ''),413 ))414 def test_min_max(self, env, source, expect):415 t = env.from_string(source)416 assert t.render() == expect417418 @pytest.mark.parametrize('name,expect', (419 ('min', '1'),420 ('max', '9'),421 ))422 def test_min_max_attribute(self, env, name, expect):423 t = env.from_string('{{ items|' + name + '(attribute="value") }}')424 assert t.render(items=map(Magic, [5, 1, 9])) == expect425426 def test_groupby(self, env):427 tmpl = env.from_string('''428 {%- for grouper, list in [{'foo': 1, 'bar': 2},429 {'foo': 2, 'bar': 3},
207 unmodified lines
modified:CHANGES+2 added
23 unmodified lines
24 `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- Add ``min`` and ``max`` filters. (`#475`_)2930.. _#469: https://github.com/pallets/jinja/pull/46931.. _#475: https://github.com/pallets/jinja/pull/47532.. _#478: https://github.com/pallets/jinja/pull/4783334Version 2.9.635-------------
505 unmodified lines