Adding the missing 'default' filter in Jekyll
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:
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
:
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.