Jesse.Is
Tips for Using Jekyll - Dec 23, 2018

I’ve used Jekyll off and on since 2013; and it took me way too long to learn these tricks. I mainly write web applications with Python + Flask. So I often find myself wishing I could use Jinja2 for my templates or use Python’s excellent documentation to find the answers. I know I could use Pelican or Flask-Freeze to generate static sites. But Jekyll is the most popular static site generator for a reason: it’s really good at most things. So below are some tips that have saved my bacon repeatedly while developing static sites for my clients.

1. Use capture to simulate content blocks

Large web projects often enforce D.R.Y. using template inheritance, which Jekyll supports out of the box via Layouts. Unlike Jinja2, however, Layouts can only render one content block. This is fine if users expect their rendered .md files to appear in a single div element on screen. But more complicated layouts like landing pages demand finesse. Not all of the marketing copy belongs in the same area. So how can we have a customer write Markdown but position it arbitrarily?

You do it by combining Liquid’s capture function with the markdownify filter. Consider the below cards:

I am a card of content.

I too am a card of content.

These are styled flexboxes whose contents have been rendered in straight markdown. Here’s what it looks like in the .md file.

{% capture block1 %}
I *am* a card of **content**.
{% endcapture %}

{% capture block2 %}
I too am a card of **content**.
{% endcapture %}

<div class="card-container">
	<div class="card">{{ block1 | markdownify }}</div>
	<div class="card">{{ block2 | markdownify }}</div>
</div>

Notice how the contents of the cards have been saved into variables block1 and block2. These variables are unstyled. However, by rendering them in double curly braces {{}} with the markdownify filter, they will be transformed into the following HTML:

<p>I <em>am</em> a card of <strong>content</strong>.</p>

I could deliver this format to a customer with instructions: to change the text in the cards, modify the markdown text in each capture block. Doing so will very closely match a similar syntax in Jinja2.

I could abstract it further using a Jekyll Include:

{% capture block1 %}
	...
{% endcapture %}

{% capture block2 %}
	...
{% endcapture %}

{% include cards.html  a=block1 b=block2}

2. Use ISO-8601 Dates in Front Matter

This one has been hugely valuable for clients. When you include a date in the Front Matter of a post or page, Jekyll cannot format it properly unless it is written in ISO 8601 format. In strftime that means:

%Y-%m-%dT%H:%M:%S+00:00

If most of your Jekyll content uses the default _posts collection then your dates are handled in the filenames. Everywhere else, ISO8601 is your friend.