Using JSON and Liquid Tags in Jekyll Templates
Jekyll allows you to write plugins to create custom generated content for your site. By default, GitHub Pages supports a few useful plugins (in the form of gems), but disables user plugins for security reasons. What if you want to get the most out of Jekyll, while still having GitHub Pages generate your site?
Plugins for GitHub Pages
To begin with, GitHub Pages supports a few useful plugins that you might want to take advantage of. For example, the
jekyll-feed plugin creates an Atom feed for subscribing to new posts. You can enable plugins on GitHub Pages by adding to your site’s _config.yml file:
Jekyll uses the Liquid templating language, which can be used in combination with the
include tag to create some fairly powerful templates. The
include tag supports passing variables to templates:
Inside the template you can access these variables using
Liquid filters include a method for formatting dates, but you’re limited to a few options that might not support what you’re looking for. I wanted to create a filter that added ordinals to the day (e.g. January 4th), but there’s no way to do this using basic Liquid filters. If your site isn’t hosted on GitHub Pages (meaning Jekyll isn’t forced into safemode), the easiest way would be to create a simple filter and place this into the
If you’re hosting your site on GitHub Pages, and don’t want to push any generated content, you can still accomplish this by using the technique above. Using some basic Liquid syntax we can write:
Save this in a file called
ordinalize.html and place it in the
_includes/ directory. To display an ordinalized date, you just need to include this template and can access the
ordinal variable as a page variable. For example, to display the date formatted as “January 4th” you could use the following:
Jekyll also supports custom data through the use of data files (YAML, JSON, or CSV) placed in the
_data directory. This allows you to avoid repeating content in your templates and can be used in a number of different scenarios.
I decided to use a JSON data file for storing SVG icons in a single place. It would be easier to use a plain SVG file, and have multiple symbols which can be referenced with
<use xlink:href="#icon-1"></use>, but browser support is slightly lacking. I ended up with a data file containing icons like this:
My icons were pretty simple in that I could construct them using just paths and fills. I then created a simple Liquid template to draw the SVGs, which accepted a parameter referencing the item in the data file:
And with these two pieces I could include them into my pages:
Unfortunately there’s no support for using site variables within data files, so you’ll have to choose the best location for your data.