I beat code into submission.

Blogging With Jekyll, Haml, Sass, and Jammit

Apr 29th, 2011

It seems anyone who uses Jekyll to run their blog ends up blogging about the particular way they’ve set it up. So here’s mine.

I came to Jekyll from Wordpress, which I found easy to set up but way too hard to change when something wasn’t quite right. The great thing about Jekyll is that it doesn’t generate anything on the fly — all HTML is generated at once, meaning your web server only has to serve raw files. Less moving parts, less things that can break.

Haml/Sass for both templates and layouts

First thing I noticed was a lack of Haml and Sass support, which simply wouldn’t do. Once you’ve had a taste of concise HTML/CSS, you never want to go back. While Jekyll doesn’t support either out of the gate, a quick Googling revealed a very simple Haml/Sass converter script, which I added in _plugins/haml_converter.rb:

So far, so good. One problem though, Jekyll doesn’t evaluate layouts through markup converters the same way it does with posts, so my layouts will have to be in plain HTML. Or will they? I stuck my haml layouts in _layouts/haml, and added a rake task, also lifted from Google, to Haml-ize any layouts:

Minify assets with Jammit

Jammit is an “industrial strength asset packaging library for Rails” which combines groups of js scripts and css files into single asset files, then runs those assets through minifiers which shrink them and hopefully makes your pages load a bit faster. Jekyll is not Rails, but you can get Jammit working without too much trouble.

First off, you need a YAML config file to configure Jammit. I put mine in _assets.yml with the following contents:

Now when I run jammit -o assets -c _assets.yml, I get nice streamlined javascript and css assets. However, one of the things Jammit does with Rails is add in helper methods for including the groups of assets into your template files. To emulate this, I had to add some special tags to Jekyll.

Jekyll uses Liquid for templating, and adding new tags in Liquid is easy. _plugins/asset_tag.rb:

And then in my layout: I can use include_css screen and include_js application.

You may have noticed Jekyll::ENV == 'production' in there. I don’t want to use my minified assets while I’m writing posts because if there’s a javascript or css problem, it’s much harder to debug minified code. So I introduce the concept of a Jekyll environment variable in _plugin/env.rb, where I simply check for the variable in the shell environment:

1

Jekyll::ENV=(ENV['JEKYLL_ENV']||'development')

And then we bring it all together in a rake task, to be run when I’m ready to push my latest changes up to my live blog: