- ``NativeEnvironment`` supports async mode. :issue:`1362`
- Template rendering only treats ``\n``, ``\r\n`` and ``\r`` as line
breaks. Other characters are left unchanged. :issue:`769, 952, 1313`
+- ``|groupby`` filter takes an optional ``default`` argument.
+ :issue:`1359`
Version 2.11.3
environment: "Environment",
value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",
attribute: t.Union[str, int],
+ default: t.Optional[t.Any] = None,
) -> "t.List[t.Tuple[t.Any, t.List[V]]]":
- expr = filters.make_attrgetter(environment, attribute)
+ expr = filters.make_attrgetter(environment, attribute, default=default)
return [
filters._GroupTuple(key, await auto_to_seq(values))
for key, values in groupby(sorted(await auto_to_seq(value), key=expr), expr)
@environmentfilter
def do_groupby(
- environment: "Environment", value: "t.Iterable[V]", attribute: t.Union[str, int]
+ environment: "Environment",
+ value: "t.Iterable[V]",
+ attribute: t.Union[str, int],
+ default: t.Optional[t.Any] = None,
) -> "t.List[t.Tuple[t.Any, t.List[V]]]":
"""Group a sequence of objects by an attribute using Python's
:func:`itertools.groupby`. The attribute can use dot notation for
<li>{{ group.grouper }}: {{ group.list|join(", ") }}
{% endfor %}</ul>
+ You can specify a ``default`` value to use if an object in the list
+ does not have the given attribute.
+
+ .. sourcecode:: jinja
+
+ <ul>{% for city, items in users|groupby("city", default="NY") %}
+ <li>{{ city }}: {{ items|map(attribute="name")|join(", ") }}</li>
+ {% endfor %}</ul>
+
+ .. versionchanged:: 3.0
+ Added the ``default`` parameter.
+
.. versionchanged:: 2.6
The attribute supports dot notation for nested access.
"""
- expr = make_attrgetter(environment, attribute)
+ expr = make_attrgetter(environment, attribute, default=default)
return [
_GroupTuple(key, list(values))
for key, values in groupby(sorted(value, key=expr), expr)
"",
]
+ def test_groupby_default(self, env):
+ tmpl = env.from_string(
+ "{% for city, items in users|groupby('city', default='NY') %}"
+ "{{ city }}: {{ items|map(attribute='name')|join(', ') }}\n"
+ "{% endfor %}"
+ )
+ out = tmpl.render(
+ users=[
+ {"name": "emma", "city": "NY"},
+ {"name": "smith", "city": "WA"},
+ {"name": "john"},
+ ]
+ )
+ assert out == "NY: emma, john\nWA: smith\n"
+
def test_filtertag(self, env):
tmpl = env.from_string(
"{% filter upper|replace('FOO', 'foo') %}foobar{% endfilter %}"