Collection: group by first letter (`first:1`), add `if count == '0'` (v2)

I'm building a Statamic v2 website and I have collection of items that need to be grouped alphabetically. Some letters don't have any entries. Let's say I have the following entries:

- Aardvark
- Addendum
- Behemoth
- Buoyancy
- Digital
- Derivative

So there are two entries starting with A, B or D and zero entries starting with C.

I have the following code in my template:

<div class="bg-danger border">
  {{ collection:my-collection }}
  {{ if title | first:1 == 'A' }}
  {{ title | wrap:p }}
  {{ /if }}
  {{ /collection:my-collection }}
</div>

This outputs the two entries starting with an A.

However, I also need a kind of section title. So the result should be:

Letter A
- Aardvark
- Addendum

Letter B
- Behemoth
- Buoyancy

Letter D
- Digital
- Derivative

First, I need to add an if count to my code somehow but I can't get it to work. That would at least allow me to go completely verbose and duplicate the code for every letter of the alphabet. The next step would be to DRY it up, but first things first.

What can I do with first:1 == 'A' and if count == '0' to 'disable' sections where no entries are rendered?

Answered by Kaz van Kooten!
>>>>>>> Answered <<<<<<<
1 Reply
1 Follower