相关文章推荐

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:

image_credit:
- creator: "Link 1"
  url: https://www.link1url.com
- creator: "Link 2"
  url: https://www.link2url.com/

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 https://vsoch.github.io/2019/jekyll-lists/ 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 https://learn.cloudcannon.com/jekyll/looping-in-liquid/

And this cheatsheet https://learn.cloudcannon.com/jekyll-cheat-sheet/

Great!

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 %}
 
推荐文章