Developers

Grouping elements by attribute value

Sometimes you have a (long) list of elements - let's say, books:

  • Fiction: The Abilene Trail by Ralph Compton and Dusty Richards
  • Travel: Italian Rustic by Elizabeth Helman Minchilli and Domenico Minchilli
  • Children's: Alphabet Soup by Scott Gustafson
  • Philosophy: The Accidental Buddhist by Dinty W. Moore
  • Fiction: Across the Nightingale Floor by Liam Hearn
  • Fiction: The accidental by Ali Smith
  • Travel: Cuba - The Sights, Sounds, Flavors, and Faces by Francois Missen
  • Philosophy: Fresh Air: Faith, Reason and Doubt by Terry Gross
  • Philosophy: The Good Luck Book by Stefan Bechtel and Laurence R. Stains
  • Children's: The Amazing Adventures of Supercat! by Kate McMullan
  • Children's: Animal Orchestra by Scott Gustafson
  • Travel: Paris Was Ours by Penelope Rowlands

This list is quite heavy on the eye.

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:

Children's

  • Alphabet Soup by Scott Gustafson
  • The Amazing Adventures of Supercat! by Kate McMullan
  • Animal Orchestra by Scott Gustafson

Fiction

  • The Abilene Trail by Ralph Compton and Dusty Richards
  • Across the Nightingale Floor by Liam Hearn
  • The accidental by Ali Smith

Philosophy

  • The Accidental Buddhist by Dinty W. Moore
  • Fresh Air: Faith, Reason and Doubt by Terry Gross
  • The Good Luck Book by Stefan Bechtel and Laurence R. Stains

Travel

  • Italian Rustic by Elizabeth Helman Minchilli and Domenico Minchilli
  • Cuba - The Sights, Sounds, Flavors, and Faces by Francois Missen
  • Paris Was Ours by Penelope Rowlands

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 }}.