The Cracked Bassoon


Toggling features in Jekyll posts

This website is written using Jekyll. Jekyll allows me to do lots of neat things, such as allow comments on blog posts, render mathematical equations, and make code blocks colorful and readable. But to do all of these things, extra resources (typically JavaScript or Liquid code) need to be included in the webpage. When these features aren’t used, such resources are simply a waste of a reader’s bandwidth.

Thankfully, there is a very simple design pattern that will allow resources to be loaded only when needed. In a new blog post, boolean variables can be included in the front matter. For example, here is the front matter of this post:

---
layout: post
title: Toggling features on/off in Jekyll posts
date: 2019-08-17
has_code: true
has_comments: true
---

Here, the line has_code: true is YAML that defines a Liquid boolean variable. I can access it from my layout file called post.md, which contains these lines:

{% if page.has_code %}
  <link rel="stylesheet" type="text/css" href="{{ "/assets/css/code.css" | relative_url }}">
{% endif %}

This is a hyperlink to ta stylesheet encapsulated within a Liquid if statement. The extra stylesheet code.css is therefore only loaded for posts on which I wish to use syntax highlighting. Granted, this particular example of this design pattern is not terribly exciting. However, it is a component of several more quite nifty features, such as dynamically building reference lists and displaying formatted code from external files. I’ll write about these in future posts.


Version history


Comments