Instructions on how to write custom placeholders for Jekyll permalinks.
How‑To: Custom Placeholders in Jekyll Permalinks
Jekyll provides a fixed set of placeholders that can be used in permalinks. Here’s how to make new ones.
I recently set up a microblog using Jekyll. One problem I had was in deciding on the permalink scheme.
My first attempt was to combine the year, month, day, hour, minute and second of each post into a single number. A post that was made on 10 February 2020 at precisely 10:00 am would have the permalink
/post/20200210100000.html. That seemed like a good choice until I noticed I’d set the time zone of my Jekyll installation incorrectly, updated it and then broke the URL of every single post.
What I wanted was to use the number of seconds since the beginning of the Unix epoch, sometimes referred to as Unix time.1 The problem is that Jekyll, the software I use to create my microblog, doesn’t provide a Unix time placeholder (here’s the list).
A lesser2 man might have stopped at this impasse. Not I. A quick consultation of Jekyll’s source reveal that the way that it supports placeholders is by using them to access instance methods of the
Jekyll::Drops::Drop class. Well, that’s an easy fix. Jekyll is written in Ruby and one of the great3 things about Ruby is the ability to reopen classes at any point and just chuck some new methods in there. Jekyll loads Ruby files in your
_plugins directory at startup so let’s write a very simple plugin.
Step 1. Create a plugins directory
There are different ways to get Jekyll to load a plugin. The simplest way is to create a
_plugins directory at the root of your site’s source directory (if you don’t already have one).
$ mkdir _plugins
Step 2. Create the plugin file
In your editor of choice, save the following in your plugins directory:
module Jekyll module Drops class UrlDrop < Drop def epoch @obj.date.strftime("%s") end end end end
Since Jekyll loads all the Ruby files in
_plugins, name it whatever you want.
I went with
Step 3. Update your Jekyll configuration
The final thing to do is update your permalink structure. Here’s mine:
:epoch as the name of my placeholder but you could choose whatever you wanted. Simply make sure that the name matches the name of the method you defined in step 2.
That’s it; you’re done! ✺