pub fn groupby(
value: Value,
attribute: Option<&str>,
kwargs: Kwargs,
) -> Result<Value, Error>
Expand description
Group a sequence of objects by an attribute.
The attribute can use dot notation for nested access, like "address.city"``. The values are sorted first so only one group is returned for each unique value. The attribute can be passed as first argument or as keyword argument named
atttribute`.
For example, a list of User objects with a city attribute can be rendered in groups. In this example, grouper refers to the city value of the group.
<ul>{% for city, items in users|groupby("city") %}
<li>{{ city }}
<ul>{% for user in items %}
<li>{{ user.name }}
{% endfor %}</ul>
</li>
{% endfor %}</ul>
groupby yields named tuples of `(grouper, list)``, which can be used instead of the tuple unpacking above. As such this example is equivalent:
<ul>{% for group in users|groupby(attribute="city") %}
<li>{{ group.grouper }}
<ul>{% for user in group.list %}
<li>{{ user.name }}
{% endfor %}</ul>
</li>
{% endfor %}</ul>
You can specify a default value to use if an object in the list does not have the given attribute.
<ul>{% for city, items in users|groupby("city", default="NY") %}
<li>{{ city }}: {{ items|map(attribute="name")|join(", ") }}</li>
{% endfor %}</ul>
Like the sort
filter, sorting and grouping is case-insensitive by default.
The key for each group will have the case of the first item in that group
of values. For example, if a list of users has cities ["CA", "NY", "ca"]``, the "CA" group will have two values. This can be disabled by passing
case_sensitive=True`.