2

I'm created an Index like page (like at the back of a book) for entries within a certain section, ordered alphabetically with the letter proceeding it.

My code below seems like a tedious way to do it, is their an easier way?

How would I handle the entries with a number as the first character (0-9) of the title?

     <h2>A</h2>

     <ul class="sub-nav">
      {% for entry in craft.entries.section('artists').search('title::A*').order('title').find() %}
        <li>...</li>
        {% endfor %}
      </ul>

    <h2>B</h2>

     <ul class="sub-nav">
      {% for entry in craft.entries.section('artists').search('title::B*').order('title').find() %}
        <li>...</li>
        {% endfor %}
      </ul>


    <h2>C</h2>

     <ul class="sub-nav">
      {% for entry in craft.entries.section('artists').search('title::C*').order('title').find() %}
        <li>...</li>
        {% endfor %}
      </ul>
4

The way to do this is with the group filter. You want to group the entries by the first character of the title.

Get the entries as an actual array

{% set allEntries = craft.entries.section('artists').order('title').find %}

Group them by first letter of title. first will return the first character of a string. upper converts a string to uppercase.

{% set groupedEntries = allEntries|group('title|first|upper') %}

Now you can loop through them:

{% for index, values in groupedEntries %}
  <h2>{{index}}</h2>
  <ul class="sub-nav">
    {% for e in values %}
      <li>...{{e}}...</li>
    {% endfor %}
  </ul>
{% endfor %}

See also this question.

  • Thanks! Edited that slightly to: {% set entriesGrouped = allEntries|group('title|slice(0, 1)|upper|replace("/[^A-Z]/", "0-9")') %} to get 0-9 rather then 0,1,2 etc. – sarah3585 Oct 16 '17 at 13:30

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.