4

I'm trying to output the alphabet where certain letters are enabled/clickable based on whether any entries from a specific section start with that letter. Here's the UI: enter image description here

Getting the A-Z is easy enough:

{% set letterArray = 'A'..'Z' %}

And I'm able to get the entries by first letter:

{% set entries = craft.entries.section('myEntries').orderBy('title asc').all() %}
{% set entriesByGroup = entries|group('title[:1]') %}
{% for firstLetter, entriesInGroup in entriesByGroup %}
    ...
{% endfor %}

I just can't figure out how to properly merge them so I can set a class or whatever on the letters that have at least an entry.

1 Answer 1

4

When looping over the letters in the range, you should be able to use the keys filter to check if the current letter is in the entriesByGroup array. If it is, you can link it or add a class, etc.

{% set letterArray = 'A'..'Z' %}
{% set entries = craft.entries.section('myEntries').orderBy('title asc').all() %}
{% set entriesByGroup = entries|group('title[:1]') %}

{% for letter in letterArray %}
   {% if letter in entriesByGroup|keys %}
      {# this letter has at least one entry, anchor link, add a class #}
   {% endif %}
{% endfor %}
 
{% for firstLetter, entriesInGroup in entriesByGroup %}
   {# your alphabetical entry listing %}
{% endfor %}

I do something similar here on the CraftQuest Archive page but with a slightly different approach (here's a video on it).

2
  • Thanks so much for the help Ryan (assuming it's Ryan 😄). I wasn't familiar with the keys filter. That did what I needed. Will definitely watch the video you linked to.
    – A Herrera
    May 17, 2021 at 3:01
  • It's me! You're welcome. :)
    – CraftQuest
    May 18, 2021 at 19:27

Your Answer

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

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