Sometimes you have a (long) list of elements - let's say, books:
But since each book has a category, the list could be made much nicer by grouping the books by category - Children's, Philosophy, Travel, Fiction etc. Like this:
The code for grouping elements:
{% grouped category_groups by category in elements %}
{% for book_category in category_groups %}
<h3>{{ book_category.first.category }}</h3>
<ul>
{% for book in book_category %}
<li>{{ book.title }} by {{ book.author }}</li>
{% endfor %}
</ul>
{% endfor %}
{% endgrouped %}
The book elements are grouped into category_groups by the value of category attribute. If there's four categories (Children's, Philosophy, Travel, Fiction), you get four separate lists of elements.
To show the title for each category, you can use {{ book_category.first.category }}.