From: David Lord Date: Tue, 23 Jul 2019 21:48:41 +0000 (-0700) Subject: clean up groupby filter docs X-Git-Tag: 2.11.0~71^2 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=refs%2Fpull%2F956%2Fhead;p=thirdparty%2Fjinja.git clean up groupby filter docs --- diff --git a/jinja2/filters.py b/jinja2/filters.py index 68f90c50..b54cff57 100644 --- a/jinja2/filters.py +++ b/jinja2/filters.py @@ -868,44 +868,41 @@ _GroupTuple = namedtuple('_GroupTuple', ['grouper', 'list']) _GroupTuple.__repr__ = tuple.__repr__ _GroupTuple.__str__ = tuple.__str__ + @environmentfilter def do_groupby(environment, value, attribute): - """Group a sequence of objects by a common attribute. + """Group a sequence of objects by an attribute using Python's + :func:`itertools.groupby`. The attribute can use dot notation for + nested access, like ``"address.city"``. Unlike Python's ``groupby``, + the values are sorted first so only one group is returned for each + unique value. - If you for example have a list of dicts or objects that represent persons - with `gender`, `first_name` and `last_name` attributes and you want to - group all users by genders you can do something like the following - snippet: + 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. .. sourcecode:: html+jinja - + - Additionally it's possible to use tuple unpacking for the grouper - (`gender` in this example) and `list`: + ``groupby`` yields namedtuples of ``(grouper, list)``, which + can be used instead of the tuple unpacking above. ``grouper`` is the + value of the attribute, and ``list`` is the items with that value. .. sourcecode:: html+jinja - - - As you can see the item we're grouping by is stored in the ``gender`` - attribute and the `list` contains all the objects that have this grouper - in common. + .. versionchanged:: 2.6 - It's now possible to use dotted notation to group by the child - attribute of another attribute. + The attribute supports dot notation for nested access. """ expr = make_attrgetter(environment, attribute) return [_GroupTuple(key, list(values)) for key, values