In the process of moving the site you’re reading from Wordpress to Jekyll, one of the things that most appealed to me was Jekyll’s plugin API. I can now say with great pleasure, that gone are the days when I’d spend hour pouring of the (not great) Wordpress plugin API docs. Not to mention that the fact there is no longer any dark corners of my life where PHP lurks, waiting to jump up and bite me in the ass.

In an attempt to get to grips with this new wonderland, I created a small plugin for Jekyll that allows you to add contextual classes to a body element. In the context of this site, it is the thing that powers the ability to have radically different styles and layouts on different pages.

The code is relativley simlple, simple add this to your _plugins directory (create it at the root of your site, if it doesn’t exist) and name it anything you like, I choose bodyClass.rb.

class BodyClassTag < Liquid::Tag  

  def generate_body_class(prefix, id)
    id = id.gsub(/\.\w*?$/, '').gsub(/[-\/]/, '_').gsub(/^_/, '') # Remove extension from url, replace '-' and '/' with underscore, Remove leading '_'

    case prefix
    when "class"
      prefix = ""
    else
      prefix = "#{prefix}_"
    end

    "#{prefix}#{id}"
  end

  def render(context)
    page = context.environments.first["page"]
    classes = []

    %w[class url categories tags layout].each do |prop|
      next unless page.has_key?(prop)
      if page[prop].kind_of?(Array)
        page[prop].each { |proper| classes.push generate_body_class(prop, proper) }
      else
        classes.push generate_body_class(prop, page[prop])
      end
    end

    classes.join(" ")
  end

end

Liquid::Template.register_tag('body_class', BodyClassTag)

Utilising it is then as simple as adding this Liquid tag to whichever layout you choose, for instance _layouts/default.html

<body class="{% body_class %}">