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
Provenance
- Commit
3ff8ec7- Tree
d149582- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
532171d- Parent 2
52dcb47
3 files changed+74 added−19 removed
modified:jinja2/filters.py+52 added-19 removed
10 unmodified lines11 import re12 import math13 import random14 15-from itertools import groupby15+from itertools import groupby, chain16 from collections import namedtuple17 from jinja2.utils import Markup, escape, pformat, urlize, soft_unicode, \18 unicode_urlencode, htmlsafe_json_dumps19 from jinja2.runtime import Undefined258 unmodified lines278 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:282+ The unique items are yielded in the same order as their first occurrence in283+ the iterable passed to the filter.284 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']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 None7 unmodified lines298 seen.add(key)299 yield item300 301 302+def _min_or_max(environment, value, func, case_sensitive, attribute):303+ it = iter(value)304+305+ try:306+ first = next(it)307+ except StopIteration:308+ return environment.undefined('No aggregated item, sequence was empty.')309+310+ 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)315+316+317+@environmentfilter318+def do_min(environment, value, case_sensitive=False, attribute=None):319+ """Return the smallest item from the sequence.320+321+ .. sourcecode:: jinja322+323+ {{ [1, 2, 3]|min }}324+ -> 1325+326+ :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)330+331+332+@environmentfilter333+def do_max(environment, value, case_sensitive=False, attribute=None):334+ """Return the smallest item from the sequence.335+336+ .. sourcecode:: jinja337+338+ {{ [1, 2, 3]|max }}339+ -> 3340+341+ :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)345+346+347 def 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 lines1127 '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 linesmodified:tests/test_filters.py+20 added
401 unmodified lines402 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+ @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() == expect417+418+ @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])) == expect425+426 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 linesmodified:CHANGES+2 added
23 unmodified lines24 `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`_)29 30 .. _#469: https://github.com/pallets/jinja/pull/46931+.. _#475: https://github.com/pallets/jinja/pull/47532 .. _#478: https://github.com/pallets/jinja/pull/47833 34 Version 2.9.635 -------------505 unmodified lines