Reputation: 776
I have a list of people (something like, in my model:
surname = models.CharField(max_length=255)
firstname = models.CharField(max_length=255)
I'd like to output a table for each starting letter of a surname. So, for example (in the template):
<table class='table'>
{% for author in content %}
<tr>
{% if author.surname|first == "A" %}
<td>{{ author.surname }}</td>
{% endif %}
</tr>
{% endfor %}
</table>
The above code works. Nevertheless, is it possible to somewhat automate the above code instead of building as many 'ifs' (and templates) as the letters of the alphabet? I'd like something like A B C D E etc... with links on each letter, and when clicking on one letter it outputs a table for the surnames starting with A B C D E etc...
Thanks in advance for any help.
Upvotes: 1
Views: 333
Reputation: 43320
You can use regroup
{% regroup content by surname.0 as authors %}
<ul>
{% for author in authors %}
<li>{{ author.grouper }}
<ul>
{% for item in author.list %}
<li>{{ item.get_surname}}</li>
{% endfor %}
</ul>
</li>
{% endfor %}
</ul>
This will regroup your content by the first character of surname, the grouper
then becomes the first letter, whilst the list
is the authors with that letter
The ordering the grouping will use is dependant on the content's order, therefore you may need to order the content by surname first before passing into your template.
Upvotes: 3