Skip to content
Myr

add default to map filter

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

authored by Kevin · committed by David Lord · parent f76c3ed · Browse files · 3 files+47 added−6 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+47 added−6 removed

  • tests:+22 added−0 removed
  • other:+25 added−6 removed

3 files+47 added−6 removed

modified:jinja2/filters.py+21 added-4 removed
57 unmodified lines
58 to lowercase and returns other types as-is."""59 return value.lower() if isinstance(value, string_types) else value606162def make_attrgetter(environment, attribute, postprocess=None):62def make_attrgetter(environment, attribute, default=None, postprocess=None):63 """Returns a callable that looks up the given attribute from a64 passed object with the rules of the environment. Dots are allowed65 to access attributes of attributes. Integer parts in paths are66 looked up as integers.
3 unmodified lines
70 def attrgetter(item):71 for part in attribute:72 item = environment.getitem(item, part)7374 if isinstance(item, Undefined) and default:75 item = default7677 if postprocess is not None:78 item = postprocess(item)7980 return item
273 unmodified lines
354 except StopIteration:355 return environment.undefined('No aggregated item, sequence was empty.')356357 key_func = make_attrgetter(355 environment, attribute,356 ignore_case if not case_sensitive else None358 environment,359 attribute,360 postprocess=ignore_case if not case_sensitive else None361 )362 return func(chain([first], it), key=key_func)363364
641 unmodified lines
1006 .. sourcecode:: jinja10071008 Users on this page: {{ users|map(attribute='username')|join(', ') }}10091010 You can specify a ``default`` value to use if an object in the list1011 does not have the given attribute.10121013 .. sourcecode:: jinja10141015 Users on this page: {{ users|map(attribute="username", default="Anonymous")|join(", ") }}10161017 Alternatively you can let it invoke a filter by passing the name of the1018 filter and the arguments afterwards. A good example would be applying a1019 text conversion filter on a sequence:10201021 .. sourcecode:: jinja10221023 Users on this page: {{ titles|map('lower')|join(', ') }}10241025 .. versionchanged:: 2.11.01026 Added the ``default`` parameter.10271028 .. versionadded:: 2.71029 """1030 seq, func = prepare_map(args, kwargs)1031 if seq:
118 unmodified lines
11501151def prepare_map(args, kwargs):1152 context = args[0]1153 seq = args[1]1154 default = None11551156 if len(args) == 2 and 'attribute' in kwargs:1157 attribute = kwargs.pop('attribute')1158 if 'default' in kwargs:1159 default = kwargs.pop('default')1160 if kwargs:1161 raise FilterArgumentError('Unexpected keyword argument %r' %1162 next(iter(kwargs)))1146 func = make_attrgetter(context.environment, attribute)1163 func = make_attrgetter(context.environment, attribute, default=default)1164 else:1165 try:1166 name = args[2]1167 args = args[3:]
96 unmodified lines
modified:tests/test_filters.py+22 added
597 unmodified lines
598 env = Environment()599 tmpl = env.from_string('{{ none|map("upper")|list }}')600 assert tmpl.render() == '[]'601602 def test_map_default(self, env):603 class Fullname(object):604 def __init__(self, firstname, lastname):605 self.firstname = firstname606 self.lastname = lastname607608 class Firstname(object):609 def __init__(self, firstname):610 self.firstname = firstname611612 env = Environment()613 tmpl = env.from_string(614 '{{ users|map(attribute="lastname", default="smith")|join(", ") }}'615 )616 users = [617 Fullname("john", "lennon"),618 Fullname("jane", "edwards"),619 Fullname("jon", None),620 Firstname("mike")621 ]622 assert tmpl.render(users=users) == "lennon, edwards, None, smith"623624 def test_simple_select(self, env):625 env = Environment()626 tmpl = env.from_string('{{ [1, 2, 3, 4, 5]|select("odd")|join("|") }}')627 assert tmpl.render() == '1|3|5'
95 unmodified lines
modified:CHANGES.rst+4 added-2 removed
14 unmodified lines
15- Python 2.6 and 3.3 are not supported anymore.16- The ``map`` filter in async mode now automatically awaits17- Added a new ``ChainableUndefined`` class to support getitem18 and getattr on an undefined object. (`#977`_)19- Allow `'{%+'` syntax (with NOP behavior) when20 `lstrip_blocks == False` (`#748`_)19- Allow ``{%+`` syntax (with NOP behavior) when20 ``lstrip_blocks == False`` (`#748`_)21- Added ``default`` param for ``map`` filter. (`#557`_)2223.. _#557: https://github.com/pallets/jinja/issues/55724.. _#765: https://github.com/pallets/jinja/issues/76525.. _#748: https://github.com/pallets/jinja/issues/74826.. _#977: https://github.com/pallets/jinja/issues/97727
611 unmodified lines