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.

1 Answer 1

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 %}
4
  • OK, that's MUCH nicer ;). Wasn't aware of the fact that slice can be used within group ...
    – Paul
    Mar 20, 2015 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, 2015 at 15:29
  • Nice. Very elegant! Mar 20, 2015 at 15:34
  • Better to add | upper {% set entriesGrouped = entries|group('title|slice(0, 1)|replace("/[^a-zA-Z]/", "0-9") | upper') %} Mar 20, 2015 at 15:40

Your Answer

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

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