My Many Colored Ways

A personal site, by Kyle Halleman.

Creating drafts in Eleventy

I typically don’t write a post in one sitting. So I need a way to save it as a draft. I use Eleventy as my static site generator of choice.

I wrote my own solution inspired by this post by Giustino Borzacchiello (Remy Sharp had a very similar solution).

But their was a problem with both of their methods. While you didn’t see the drafts in your post list, you also didn’t see them in development. When I write my posts I want a preview of what they will look like on my actual site. I want to see them in my post list in development.

publishedPosts collection

The publishedPosts collection logic is similar. I didn’t like the idea of adding a new property to the “schema” of the frontmatter though. I felt it was more idiomatic to use the tags property and add a tag of draft if it was supposed to be a draft.

---
title: Creating drafts in Eleventy
date: 2021-02-09
tags: draft
---
eleventyConfig.addCollection("publishedPosts", function (collectionApi) {
const now = new Date();
return collectionApi
.getFilteredByTag("posts")
.filter((post) => post.date <= now && !post.data.tags.includes("draft"));
});

Seeing drafts in development

Now I have my published posts, but I want to see all posts in development. My site is based on eleventy-high-performance-blog. In both my archive and index pages, I create my postslist collection like so:

{% if isdevelopment %}
{% set postslist = collections.posts %}
{% else %}
{% set postslist = collections.publishedPosts %}
{% endif %}
{% include "postslist.njk" %}

The isdevelopment variable comes from this file in _data in eleventy-high-performance-blog.

Keeping drafts out of tags

I don’t want drafts to show up in my tags page. That would defeat the purpose.

Luckily, filtering tags is pretty straighforward. Add whatever tag you don’t want to show up to your filter frontmatter in your tag template.

pagination:
filter:
- draft

Having the ability to write drafts of blog posts without them being public is the main reason the repo for this site is private. Maybe that’s childish of me—not wanting all three people that read this to see the stupid shit I end up cutting.

Either way, now you know how to create drafts and still get to view them while working locally.