1

I am trying to loop through a list of categories to add some text to the page. If it is the last item I want to replace the ',' with the words 'and' but only adda a ',' if there are more than 2 categories.

{% set categories = craft.categories.group('products') %}
{% for category in categories %}
    {{ loop.last ? 'and ' }}{{ category.title }}{{ loop.index > 2 ? ', ' }}
{% endfor %}

if there is only category it would output:
hello

So if there are two categories it would output:
hello and world

if there are 3 or more it would output:
hello, world and space

My current code looks like this. but isn't quite working correctly. Anyone able to help? or point in the right direction?

Thanks.

2

The way I would think of it is: I print the category title, then if this is not the last category I print the separator (and or ,). I would use the loop variable revindex to distinguish the next-to-last category (which gets the and) from the others (which get the ,). loop.revindex is like loop.index except that it counts the number of iterations from the end. So your code starts to look like this:

{% for category in categories %}
  {{category.title}}
  {% if not loop.last %}
    {{ loop.revindex == 2 ? ' and' : ',' }}
  {% endif %}
{% endfor %}

That code will leave a space before the ,, which you can fix by sticking everything on one line:

{% for category in categories %}
  {{category.title}}{% if not loop.last %}{{ loop.revindex == 2 ? ' and' : ',' }}{% endif %}
{% endfor %}
  • Thanks Marion. I hadn't considered the revindex. This is useful. – Terry Upton Jul 25 '16 at 16:31
  • I don't think I've every used revindex - but now I know what it's for! – Marion Newlevant Jul 25 '16 at 16:36
  • First time I've heard of it, too! – Brad Bell Jul 25 '16 at 16:58

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.