Django: Using regroup template tag to group a list by letter

Sometimes the easy part is pulling data out but the hard part is actually displaying it nicely.

On some index pages, you can often categorise the list by the first letter of the name. This makes it a lot easier to find the information you're after.

For example, displaying a list of apps in an index page.

We use the built-in tag "regroup" to do this.

{% regroup apps by name.0 as apps_by_letter %}

The list of apps is contained in the variable "apps". We group it by "name.0", which is the first letter of the name into a new context variable called "apps_by_letter".

Note: Make sure that "apps" is sorted by name prior to calling regroup! Otherwise your list is going to be scattered.

<div id="apps_section_list">
{% for letter_apps in apps_by_letter %}
<div class="letter"><b>{{ letter_apps.grouper }}</b></div>

<ul>
{% for app in letter_apps.list %}
<li> 
<a class="image" href="{{ app.url }}"><img src="{{ app.image }}"></a>
<a href="{{ app.url }}">{{ app.name }}</a>
</li>
{% endfor %}
</ul>
{% endfor %}
</div>

We then proceed to loop each item in "apps_by_letter" as "letter_apps", which gives us the first letter which contains apps and the list of apps in this group.

The category label is stored in "letter_apps.grouper" while the list of apps is stored in "letter_apps.list".

See also a more advanced tutorial about grouping by date.

 
Copyright © Twig's Tech Tips
Theme by BloggerThemes & TopWPThemes Sponsored by iBlogtoBlog