Canonical Post Urls in Jekyll

In the next couple of days I'll be contributing a series of blog posts to the Atlassian Developers blog to serve as a backdrop for my presentation at Atlassian Summit 2015, about a week and a half from now1. I wanted to syndicate that content here, but for SEO reasons I was asked to mark the Atlassian URL as the canonical one for each post. That isn't possible out of the box, so here's how I modified my Jekyll template to accommodate this change:

First, I add a canonical-url tag to my YAML front-matter:


And second, I modified my header template to set the canonical variable and populate the proper <link ...> tag:

{% if page.canonical-url == nil %}
{% capture canonical %}{{ site.url }}{% if site.permalink contains '.html' %}{{ page.url }}{% else %}{{ page.url | remove:'index.html' | strip_slash }}{% endif %}{% endcapture %}
{% else %}
{% assign canonical = page.canonical-url %}
{% endif %}
<link rel="canonical" href="{{ canonical }}">

The documentation out there for liquid is somewhat less helpful than I'd prefer, so the proper way to test if a variable was truly unset took a few stabs, and getting the proper context for the page variable, despite pages really being posts, was also unintuitive. One of these days, I might have to give up on Jekyll based purely on the "clear as mud" factor.

NB: Getting the above Liquid code to actually display was a royal pain in the butt. This site was helpful, and I appreciated his closing sentence:

Displaying liquid code in jekyll is really an annoying task. So try to avoid it as much as you can.

  1. Holy crap.

Oct 27th, 2015