I’m Paul Herron, a full-stack developer and technical manager.
I focus mainly on back-end development with tools like Symfony
and devops with tools like Docker

Adding the missing 'default' filter in Jekyll

by Paul Herron on 27 January 2014

A great little filter recently made its way into the Liquid templating system that makes it easy to output a default value if the variable you pass it turns out to be empty. Take this example of a metatag where I want to output the page title if it’s populated, otherwise I want to output some default value instead:

<meta property="og:title" content="{{ page.title | default: 'Paul Herron, Web Developer' }}" >

It’s a lot more elegant than putting that same logic inside if/else blocks.

On most pages of my site, page.title is populated, so is output. On the homepage, though, it’s unset so the default string “Paul Herron, Web Developer” is output instead.

I was scratching my head trying to work out why this wasn’t working in Jekyll, and it looks like this new feature hasn’t landed yet in the version of Liquid that Jekyll uses. That’s easily remedied by knocking up a quick plugin that takes the new default method as-is from Liquid, and saving it at _plugins/default_filter.rb:

module Jekyll
  module DefaultFilter

    def default(input, default_value = "")
      is_blank = input.respond_to?(:empty?) ? input.empty? : !input
      is_blank ? default_value : input



I’m sure this feature will arrive soon in the Jekyll core, but for the moment this gets around around the issue!

I’ve put the plugin on GitHub.

Back to homepage Back to blog listing