sjkblog

Django block equivalent in Jekyll

Posted on 25 Oct 2013.

Django has an excellent way of passing content from a page template to whatever base template it is extending. They call it ‘blocks’ and it’s a very handy feature. Let’s, for example, say you have all your css stylesheet includes in the head section of your base html template. But what if some pages require an extra css file, let’s call it extras.css, that most other pages don’t need? Easy, set up your base template to include a block called head_extra (or whatever you want to call it):

<!-- This is your base template -->
<html>
    <head>
        <title>Hello!</title>
        {% block head_extra %}{% endblock %}
    </head>
    ...

Now pass the css include to your base template in whatever file that extends it:

{% extends 'base.html' %}

{% block head_extra %}
<link href="css/extras.css" rel="stylesheet">
{% endblock %}
...

The end result will, as you already might have figured out, be:

<html>
    <head>
        <title>Hello!</title>
        <link href="css/extras.css" rel="stylesheet" rel="stylesheet">
    </head>
    ...

Today I found the need for this functionality, which surprisingly doesn’t seem to exist in stock Jekyll. Don’t worry though, there is a plugin that remedies this problem and it is called Jekyll-contentblocks. Getting it working is easy as pie. Start off by adding the gem to your project’s Gemfile:

gem 'jekyll-contentblocks'

Then install it with bundle:

$ bundle install

Make sure you somehow initialize Bundler. One can do this by writing a three line ‘plugin’. Put the following in your yourproject/_plugins/bundler.rb. You might have to create the _plugins directory. The file should contain the following:

require "rubygems"
require "bundler/setup"
Bundler.require(:default)

You may now use the liquid tags contentblock and contentfor to pass information. The above Django examples translated to Jekyll would look like the following:

<!-- This is your base template -->
<html>
    <head>
        <title>Hello!</title>
        {% contentblock head_extra %}
    </head>
    ...
---
- layout: default
---
{% contentfor head_extra %}
<link href="css/extras.css" rel="stylesheet">
{% endcontentfor %}
...

The end result is naturally the same as in the Django example.

blog comments powered by Disqus