Jekyll pages have a metadata field date, which can be set to show when they were updated1. For the homepage, I wanted it to be the current (at build time) date. I could have manually changed it each time, but that’s annoying and easy to forget. This also seemed like a task I could easily automate.

https://xkcd.com/1205
XKCD 1205: Is It Worth the Time?

So, let’s start by looking at the front matter of a page. The frontmatter is the part between the --- at the top of a Markdown file. Jekyll treats it specially and lets you set the post’s title, date, tags, and other properties.
The body of a blog post is Liquid, and in there, I simply could have used {{ site.time }} , but the frontmatter is YAML and not liquefied that way.

This problem has been encountered before. Unfortunately, none of the mentioned solutions worked directly for me, but from the last one, I got the idea of writing a plugin.

So I looked at the excellent docs and quickly pieced together a plugin that evaluates any values in frontmatter looking like eval(<code>). The code is extracted with a regex and then passed to Ruby’s eval function. For example date: 'eval(site.time.strftime("%Y-%m-%d %H:%M:%S"))' will be evaluated to the current date. As the code inside eval is executed in the context of the generator, it has access to all variables and methods it needs, like the current page or the entire site. Obviously, this allows arbitrary code execution, so I marked the generator is as safe false.

I didn’t have experience with Ruby before, but the plugin was pretty simple, and Ruby uses the same concepts as other languages I already know. Judging by the bit of code I wrote, it’s an excellent language, and I might take a look at it again in the future.
The entire source code is available on GitHub if you want to use it.

  1. I’ve since found out the date tag is used in the metadata as first published on, so I’ve set it to the correct non-dynamic date for the homepage. The update tag is called last_modified_at

Comments