Target first and last items and append if greater than 2 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 &gt; 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.
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 %}