4

I would like to build an alphabetical list of craft entries, but group them by the initials of one field of each entry. Thus, getting some kind of alphabetical index, like

A

  • Apples
  • Ananas

B

  • Beer

How do I do that?

1 Answer 1

10

First, sort all entries by multiple criteria:

{# get our entries and order by firstname, lastname #}
{% set allEntries = craft.entries.section('entries').orderBy('lastname asc, firstname asc').all() %}

Then use craft's custom "group" filter (lastname[:1] picks the first letter):

{# group them by the first letter of the last name https://docs.craftcms.com/v3/dev/filters.html#group #}
{% set allEntriesByGroup = allEntries | group('lastname[:1]') %}

Then loop through that multidimensional array (firstletter, entriesInGroup) is key -> value in twig:

{% for firstletter, entriesInGroup in allEntriesByGroup %}
    <h3>{{firstletter}}</h3>
    <ul>
    {% for entry in entriesInGroup %}
       <li>{{entry.lastname}}, {{entry.firstname}}</li>
    {% endfor %}
    </ul>
{% endfor %}
2
  • The reason I'm posting it is I first thought I had to do the array manipulation in twig – but then found out twig doesn't really support that, by design – and finally, found out craft provides a great set of tools on top of twig like those custom filters
    – Urs
    Aug 26, 2018 at 6:43
  • Here's another option from a previous SE thread: craftcms.stackexchange.com/a/22397/278 (not updated for Craft 3).
    – CraftQuest
    Aug 27, 2018 at 2:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.