7

Probably going to be an easy win for someone here, but being able to do this is currently eluding me. So:

I'm trying to output a list of Artist names grouped by first letter but need to ignore 'The ' when it appears at the start of an Artist name.

To do this, I've added a 'Sort Title' field to the Artist entry (as I figured there might be other occasions where this could be useful) - and using Brad's answer here this works fine when outputting a standard alphabetical list.

However, there's also a page that needs to display the Artists grouped by first letter. Code for that currently is:

{% for letter, artists in craft.entries.section('lineup').order('title') | group('title|upper|slice(0, 1)') %}

How best could I adapt that to use my sortTitle field (when it isn't empty) to group the Artist entries? I get 'Expected name or number' if I try to use Brad's code in place of 'title'.

7

That SQL code snippet Brad posted only works with the order parameter. The group filter doesn't allow SQL, but you could try to replicate the logic using Twig's ternary operator.

{% set artists = craft.entries.section('lineup').order('(CASE WHEN field_sortTitle IS NULL OR field_sortTitle = "" THEN title ELSE field_sortTitle END)') %}
{% set artistsGrouped = artists|group('{ object.sortTitle ? object.sortTitle[:1]|upper : object.title[:1]|upper }') %}

{% for letter, artistsInGroup in artistsGrouped %}
    {{ letter }}
    {% for artist in artistsInGroup %}
        {{ artist.title }}
    {% endfor %}
{% endfor %}

To shorten the expression a bit I used the slice filter's short syntax [:1] instead of |slice(0, 1).

|improve this answer|||||
  • Thanks for the answer but that's not working for me I'm afraid. It outputs the lists of Artists but doesn't display the letter at the top of each. Doesn't seem to like the ternary operator in the group command. – Rob Webb Mar 14 '15 at 17:21
  • This is what I'm aiming for: B The Beatles Belle & Sebastian Broken Bells C Caribou The Cars Chic – Rob Webb Mar 14 '15 at 17:25
  • The shortcut syntax (i.e. {title}) to access the entry in the group filter appears to have problems with ternary operators. But it is also possible to access the entry via a variable object with normal Twig syntax (i.e. {{ object.title }}). You can then use any expression you like to, including ternary. The syntax within the filter looks a bit weird, because it already adds one pair of curly brackets for you (i.e. title and { object.title }). – carlcs Mar 14 '15 at 19:44

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.