Hacking a Routing Component in Jekyll

Originally published at: http://www.sitepoint.com/hacking-routing-component-jekyll/

Initially I was going to title this article Hacking a routing component in Jekyll when hosted on GitHub Pages with Markdown, Liquid, and YAML. Obviously, that’s a bit long so I had to shorten it. Anyway, the point doesn’t change: Jekyll lacks some kind of router, and I think I found a not-so-terrible solution to mimic one.

But first things first: I come from a Symfony background, so by router I mean a component that maps URLs to names — a.k.a. routes – so you can safely change a URL without having to crawl your codebase to update all the links heading to the obsolete location.

Why would we need such a thing?

I am currently working hard on the docs for SassDoc v2 (not released yet, as of this writing). We have quite a bit of content; over 20 pages split across 4 different sections containing many code examples and cross references.

A couple of times during the rewriting, I desired to change a URL. Problem is, when I change a URL I have to update all the links heading to this URL if I don’t want them to be broken. Crawling over 20 pages to make sure all URLs are alright is far from ideal…

This is why we need a routing component. Then we would refer to URLs by name rather than by their path, allowing us to change a path while keeping the name perfectly valid.

How does it work?

So what do we need to make this work? If you are running Jekyll but are not restricted to safe mode (which is unfortunately the case when using GitHub Pages for hosting), you can surely find/build a Ruby plugin to do this. This would be the best solution since this is typically something handled by a server-side language.

Now, if you host your site on GitHub Pages which is more often the case than not with Jekyll, you cannot use plugins nor can you extend Jekyll’s core with custom Ruby code, so you end up hacking a solution with what’s available: Liquid and Markdown.

The main idea is to have a file containing all our routes mapped to actual URLs. Thankfully, Jekyll allows us to define custom global variables through YAML/JSON/CSV files stored in the _data folder, later accessed via site.data.<filename>. Thus we can access those URLs directly in our pages from their name.

To add a little syntactic sugar on top, we’ll create Markdown link references that will allow a friendlier syntax – but let’s not go too fast too quickly.

Continue reading this article on SitePoint

Great article as usual.

A smart trick, but jekyll-redirect-from can be an alternative solution, and in addition, it is one of the GitHub Pages white-listed plugins.