Separate items in array with commas (except last)

I created an image crediting snippet to use in blog posts that inserts links at the bottom of posts. The block of front matter looks like this:

- creator: "Link 1"
- creator: "Link 2"

What I was trying to do is like this, to insert a list of formatted links to those references:

{% if page.image_credit %}
    Image credits:
    {% for image in page.image_credit %}
    <a href="{{ image.url }}" title="{{ image.creator }}">{{ image.creator }}</a>
    {% endfor %}
{% endif %}

What I’m trying to achieve is to insert a comma or separator character in between the items in the loop, but not after the final item… to somehow exempt the last item. Is there a way to stick an if inside of this loop to check if the item is last and do something different?

Indeed there is a way. There are methods available as forloop.first, forloop.last and forloop.index to tell you where you are in the loop. Note that gere forloop is that literal name.

I came across this before and found an example now. So now add this between you text and endfor.

{% if forloop.last %}{% else %},{% endif %}

Copied from You make it even shorter by taking out the else and using if not true logic.

See also this looping tutorial which a .first and .last section

And this cheatsheet

1 Like

This is great! Already went and added it and works perfectly.

Thanks for the tip!


Also I happened to come across this yesterday so wanted to add an equivalent to the above - since unless is a great way Ruby/Jekyll to negate an if condition.

{% unless forloop.last %},{% endif %}
1 Like