2

I'm trying to output a list of Brand names grouped by first letter. But some items have a number or symbol in the name. I want to list first the Numbers and symbols under 0-9 and the rest of the brands under A-Z

Like this:

0-9

  • +People
  • 10 Days
  • 2Two
  • 40 Weft
  • 55 DSL
  • 81hours

A

  • Acne
  • Adidas

B

  • B.Young
  • etc etc.
5

To group by the first letter you would simply use the slice filter within Craft's group filter.

For all non letter characters you can now use Craft's replace filter (it does regex since Craft 2.2) and replace them with whatever you want these entries to be sorted by.

{% set entriesGrouped = entries|group('title|slice(0, 1)|upper|replace("/[^A-Z]/", "0-9")') %}

{% for letter, entriesInGroup in entriesGrouped %}
    {{ letter }}
    {% for entry in entriesInGroup %}
        {{ entry.title }}
    {% endfor %}
{% endfor %}
  • OK, that's MUCH nicer ;). Wasn't aware of the fact that slice can be used within group ... – Paul Mar 20 '15 at 15:26
  • I found out some days ago, that you can even go crazy and do things like ternary in there: Sorting entries A-Z, ignoring 'The' and grouping by first letter – carlcs Mar 20 '15 at 15:29
  • Nice. Very elegant! – Michael Rog Mar 20 '15 at 15:34
  • Better to add | upper {% set entriesGrouped = entries|group('title|slice(0, 1)|replace("/[^a-zA-Z]/", "0-9") | upper') %} – Johannes Lamers Mar 20 '15 at 15:40

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.