Jekyll: generate body class

(This is an auto copy over from my old blog at Joe8bit.com, some links may be broken)

Adding a Liquid tag to generate contextual classes

In the process of moving the site you’re reading from WordPress to Jekyll (NB: lol and back again), 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 %}">;
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s