0

I've got a for loop that is returning the first letter of the entry title. I have a number of entries so I almost get a complete alphabet except that there are too many of many letters. I only want one 'a', one 'b', one 'c' and so forth. And no letter if there is no entry to correspond to it.

{% for alpha in craft.entries.section('advertisers').order('title asc') %}
    <a href="{{ siteUrl }}{{ alpha.title|first }}">{{ alpha.title|first }}</a>
{% endfor %}

This code returns: A A A B B B B B C C E E E E G G H H K M M M M P P R R S S S T T U U U W W but I want it to return A B C E G H K M P R S T U W

Are there any solutions to this?

2
  • Correct me if I'm wrong, but the only code relevant to your question is the first for loop, right?
    – Brad Bell
    Commented Mar 31, 2017 at 23:08
  • yup. I removed some code to clean it up. I'm still learning the ways of Stackexchange.
    – afc
    Commented Mar 31, 2017 at 23:21

2 Answers 2

2

If you need only unique letters, you can build a new array and only merge first letters that are not already in the array like this:

{% set letterArray = [] %}

{% for alpha in craft.entries.section('advertisers').order('title asc') %}
  {% if alpha.title|first not in letterArray %}
    {% set letterArray = letterArray|merge([alpha.title|first]) %}
  {% endif %}
{% endfor %}

{% for letter in letterArray %}
  <a href="{{ siteUrl }}{{ letter }}">{{ letter }}</a>
{% endfor %}
0
1

Completely untested, but something like this should work:

{% set letterArray = [] %}

{% for alpha in craft.entries.section('advertisers').order('title asc') %}
    {% set letterArray = letterArray|merge([alpha.title|first]) %}
{% endfor %}

{% for letter in letterArray %}
    <a href="{{ siteUrl }}{{ letter }}">{{ letter }}</a>
{% endfor %}
4
  • I am getting this error: "The merge filter only works with arrays or "Traversable", got "string" as second argument."
    – afc
    Commented Apr 6, 2017 at 1:12
  • I did say it wasn't tested... try the updated answer.
    – Brad Bell
    Commented Apr 6, 2017 at 2:51
  • No error but still returns the same as my original code. The suggestion by Alex worked perfect. I appreciate your assistance!
    – afc
    Commented Apr 8, 2017 at 1:00
  • Foiled by @AlexRoper yet again!
    – Brad Bell
    Commented Apr 8, 2017 at 3:36

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.