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
Provenance
- Commit
2319cd5- Tree
33e5a12- Author
Kevin <krbiggers@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent
f76c3ed
3 files changed+47 added−6 removed
modified:jinja2/filters.py+21 added-4 removed
57 unmodified lines58 to lowercase and returns other types as-is."""59 return value.lower() if isinstance(value, string_types) else value60 61 62-def make_attrgetter(environment, attribute, postprocess=None):62+def 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 lines70 def attrgetter(item):71 for part in attribute:72 item = environment.getitem(item, part)73 74+ if isinstance(item, Undefined) and default:75+ item = default76+77 if postprocess is not None:78 item = postprocess(item)79 80 return item273 unmodified lines354 except StopIteration:355 return environment.undefined('No aggregated item, sequence was empty.')356 357 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)363 364 641 unmodified lines1006 .. sourcecode:: jinja1007 1008 Users on this page: {{ users|map(attribute='username')|join(', ') }}1009 1010+ You can specify a ``default`` value to use if an object in the list1011+ does not have the given attribute.1012+1013+ .. sourcecode:: jinja1014+1015+ Users on this page: {{ users|map(attribute="username", default="Anonymous")|join(", ") }}1016+1017 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:1020 1021 .. sourcecode:: jinja1022 1023 Users on this page: {{ titles|map('lower')|join(', ') }}1024 1025+ .. versionchanged:: 2.11.01026+ Added the ``default`` parameter.1027+1028 .. versionadded:: 2.71029 """1030 seq, func = prepare_map(args, kwargs)1031 if seq:118 unmodified lines1150 1151 def prepare_map(args, kwargs):1152 context = args[0]1153 seq = args[1]1154+ default = None1155 1156 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 linesmodified:tests/test_filters.py+22 added
597 unmodified lines598 env = Environment()599 tmpl = env.from_string('{{ none|map("upper")|list }}')600 assert tmpl.render() == '[]'601 602+ def test_map_default(self, env):603+ class Fullname(object):604+ def __init__(self, firstname, lastname):605+ self.firstname = firstname606+ self.lastname = lastname607+608+ class Firstname(object):609+ def __init__(self, firstname):610+ self.firstname = firstname611+612+ 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"623+624 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 linesmodified:CHANGES.rst+4 added-2 removed
14 unmodified lines15 - 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`_)22 23+.. _#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