josephdyer/skeleventy

nunjuck get latest 3 posts

cleocadio opened this issue · 1 comments

Hey There, loved this boilerplate and building my 1st blog using jamstack with this.

I wanted to put the latest 3 posts on index page, but can´t find it on any documentations in nunjucks
When you iterate this: {% for post in collections.blog %} you get all posts.
Is there any way I can modify this to just get the last 3?

Thanks

@cleocadio You could add your own filter to eleventy that would let you do this.

Add this code to .eleventy.config.js under the other calls to addFilter (around line 10)

eleventyConfig.addFilter("head", (array, n) => {
  if (n < 0) {
    return array.slice(n);
  }

  return array.slice(0, n);
});

then you can change

{% for post in collections.blog %}

to

{% for post in collections.blog | head(-3) %}

it is -3 here as the posts are sorted by date with the oldest post first, so you want to take three posts from the end of the collection to get the 3 newest ones.

(The code for the head filter was 'borrowed' from https://github.com/11ty/eleventy-base-blog)