1

I have a A-Z menu to filter entries by their first letter.

   <ul class="directory-letters">
    <li class="all current" data-filter="all">ALL</li>
    {% for entry in craft.entries.section('membershipDirectory').order('title asc') %}
      <li data-filter="letter-{{ entry.companyName|slice(0, 1)|lower|replace("/[^a-z]/", "0-9") }}">{{ entry.companyName|slice(0, 1) }}</li>
    {% endfor %}
   </ul>

Issue I have is if there are 4 entries beginning with 'C' the output will be:

A B C C C C D E F...

Can I limit each letter once so I'll get 1 'C' is there are 1+ entries starting with 'C'?


UPDATE:

I'm now getting the right number of instances created but no text inside my

  • . Likely a rookie error somewhere:

    {% set allEntries = 
    craft.entries.section('membershipDirectory').order('title asc') %}
    {% set allEntriesByFirstCharacter = 
     allEntries|group('companyName|slice(0, 1)|lower|replace("/[^a-z]/", 
     "0-9")' ) %}
    
     <ul class="directory-letters">
        <li class="all current" data-filter="all">ALL</li>
        {% for allEntries in allEntriesByFirstCharacter %}
           <li data-filter="letter-{{ entry.companyName|slice(0, 1)|lower|replace("/[^a-z]/", "0-9") }}">{{ entry.companyName|slice(0, 1)|lower|replace("/[^a-z]/", "0-9") }}</li>
      {% endfor %}
    </ul>
    
    1

    You can use the group filter and create a 2d array with the letter as the first index and the entries as second index.

    {% set allEntriesByFirstCharacter = allEntries|group('companyName|slice(0, 1)|lower|replace("/[^a-z]/", "0-9")' ) %}
    

    The string passed in the filter will get rendered as an object template an equal results will be grouped by the same key.

    • Thank you! I'm getting empty outputs, but the right number of instances now. Post updated. – sarah3585 Oct 30 '18 at 16:57
    • Where do you assign the entry variable? You use it but I'm not sure what it should be. Please take a look at the link – Robin Schambach Oct 30 '18 at 16:59

    Your Answer

    By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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