Post Navigation - next and previous

One thing I didn't get at all, looking at the eleventy starter projects, was how to recreate the "next post" and "previous post" links similar to the ones on my Gatsby blog. Following their twitter account was a good idea, because about a week ago they promoted a post Bryce Wray wrote this post, inspired by Pascal W..

Once you look at their solution -- adding a prevPost and nextPost to each item in a collection array -- it seems perfectly obvious. But it wasn't obvious until they came up with it. It's as simple as taking the array of posts (or whatever collection you want to work on), step through that array, and add a "next" and/or "previous" key to each item, with the index of the next/previous item.

After a few minutes of pondering, I realized it wasn't any different from my Gatsby blog. The same idea, applied in the same way, just slightly different syntax.


  eleventyConfig.addCollection("posts", function(collection) {
    const coll = collection.getFilteredByTag("posts");

    for (let i = 0; i < coll.length; i++) {
      const prevPost = coll[i - 1];
      const nextPost = coll[i + 1];

      coll[i].data["prevPost"] = prevPost;
      coll[i].data["nextPost"] = nextPost;
    }

    return coll;
  });

UPDATE:

and then the next day I realized I was going to want to do this to multiple collections, so I wrapped the whole thing above inside a function called makeNavsOnPosts. Feed it your collection's string-name, and it does it all for you.

So far I've got makeNavsOnPosts("posts"); and makeNavsOnPosts("seattle-2019"); I'm sure I'll need at least 2 or 3 more by the time I convert all the old stuff over.