Question about site.posts values

Probably a dumb question - I’m trying to get the first and last post for my site. I’m using this to capture the posts:

{% capture lastPost %}{{ site.posts | first }}{% endcapture %}
{% capture firstPost %}{{ site.posts | last }}{% endcapture %}

But if I {{lastPost.title}} I get nothing. I then noticed that if I did {{lastPost}} I got the rendered output of the post itself. How would I get the post “object” instead?

And duh - now I see it. I’m rendering the page. Sigh. So let me say this - I was able to output the last page title and date like so:

{{ site.posts[0].title }} ({{ site.posts[0].date | date: "%Y-%m-%d" }})

But every attempt to get the last value of site.posts has failed for me. I tried site.posts[site.posts.size-1] but that returned nothing.

I’ve tried this to get the “last index”:

{% capture lastdx %}{{ site.posts.size | minus: 1 }}{% endcapture %}

if I output lastdx, I get 61. If I do:

{{ site.posts[lastdx].title }

I get nothing. If I change lastdx to a hard coded value of 61, it works.

Not tested, but I think capture assigns the variable as a string, which could explain why it’s not working since it expects a number.

Maybe try filtering lastdx with something like {{ lastdx | abs }} before you try to call it on site.posts to convert the string to a number.

You could also use assign which might be cleaner.

{% assign lastdx = site.posts.size | minus: 1 %}

Oh and even simpler are first and last. Use dot notation and you can access the entire object.

In your case {{ site.posts.first.title }} and {{ site.posts.last.title }} will get the title of the first and last posts. You can replace title with any variable available in the post’s YAML Front Matter… date, content, excerpt, etc.

Awesome - all of these answers helped me learn a bit. Thank you!

1 Like