diff options
-rw-r--r-- | CHANGES.rst | 2 | ||||
-rw-r--r-- | src/jinja2/filters.py | 2 | ||||
-rw-r--r-- | tests/test_filters.py | 8 |
3 files changed, 11 insertions, 1 deletions
diff --git a/CHANGES.rst b/CHANGES.rst index f1e0ee0..c53d67e 100644 --- a/CHANGES.rst +++ b/CHANGES.rst @@ -30,6 +30,8 @@ Unreleased has been updated to be more efficient and match more cases. URLs without a scheme are linked as ``https://`` instead of ``http://``. :issue:`522, 827, 1172`, :pr:`1195` +- Filters that get attributes, such as ``map`` and ``groupby``, can + use a false or empty value as a default. :issue:`1331` Version 2.11.3 diff --git a/src/jinja2/filters.py b/src/jinja2/filters.py index 9fb52ed..7c95dce 100644 --- a/src/jinja2/filters.py +++ b/src/jinja2/filters.py @@ -67,7 +67,7 @@ def make_attrgetter(environment, attribute, postprocess=None, default=None): for part in attribute: item = environment.getitem(item, part) - if default and isinstance(item, Undefined): + if default is not None and isinstance(item, Undefined): item = default if postprocess is not None: diff --git a/tests/test_filters.py b/tests/test_filters.py index 3cd0fdd..efc82bc 100644 --- a/tests/test_filters.py +++ b/tests/test_filters.py @@ -666,6 +666,12 @@ class TestFilter: tmpl = env.from_string( '{{ users|map(attribute="lastname", default="smith")|join(", ") }}' ) + test_list = env.from_string( + '{{ users|map(attribute="lastname", default=["smith","x"])|join(", ") }}' + ) + test_str = env.from_string( + '{{ users|map(attribute="lastname", default="")|join(", ") }}' + ) users = [ Fullname("john", "lennon"), Fullname("jane", "edwards"), @@ -673,6 +679,8 @@ class TestFilter: Firstname("mike"), ] assert tmpl.render(users=users) == "lennon, edwards, None, smith" + assert test_list.render(users=users) == "lennon, edwards, None, ['smith', 'x']" + assert test_str.render(users=users) == "lennon, edwards, None, " def test_simple_select(self, env): env = Environment() |