Skip to content

Hiding posts with future dates in Eleventy

In static site generators like Jekyll, you can generate posts with a future date using a flag. When you build on your local machine, provide that flag to view future posts. Later, when you publish your blog, you can skip future posts. It is a handy feature when you build your website every day using IFTTT or something similar.

In Eleventy, there is no such flag. Here is a technique I use to get a similar result with Eleventy.

Let’s use an environment variable, ELEVENTY_ENV, to distinguish between local machine (development) and blog (production) environment.

# Development
$ npx @11ty/eleventy --serve

# Production
$ ELEVENTY_ENV=production npx @11ty/eleventy

To hide the post, we need to set two data variables on each page, permalink and eleventyExcludeFromCollections, based on the page date and environment:

  • set permalink to false to disable writing the file to the output folder.
  • set eleventyExcludeFromCollections to true, to exclude from collections as the variable name suggests.

We can set these data variables to all pages using eleventyComputed feature. Create a JavaScript file in the path _data/eleventyComputed.js, and add these lines:

/* _data/eleventyComputed.js */
const isPageFromFuture = ({ date }) =>
process.env.ELEVENTY_ENV === "production" && date.getTime() > Date.now();

module.exports = {
permalink: (data) => {
const { permalink, page } = data;
if (isPageFromFuture(page)) return false;

return permalink;
},
eleventyExcludeFromCollections: (data) => {
const { eleventyExcludeFromCollections, page } = data;
if (isPageFromFuture(page)) return true;

return eleventyExcludeFromCollections;
},
};

The isPageFromFuture() returns true when the environment is production, and the current page has a future date. Based on that value we set permalink and eleventyExcludeFromCollections data variables.

Now, try building your blog with and without the environment variable ELEVENTY_ENV=production.

I’m available for new projects from October 2021.

Get in touch