Clutching at Security Blankets

Lessons learned while working in Information Security.

moc.navat@ymerej

Creating a custom liquid tag for Jekyll


20 August 2015

In Things I Need To Create For This Blog I mentioned that I needed an easier way to create sidenotes than pasting in a bunch of ugly HTML in my Markdown. So, following the super simple template on the Jekyll page and not knowing any Ruby, I created a Sidenote liquid tag.

require 'securerandom'

module Jekyll
  class SidenoteTag < Liquid::Tag

    def initialize(tag_name, text, tokens)
      super
      @text = text
    end

    def render(context)
	  id = SecureRandom.random_number(36**12).to_s(36).rjust(6, "0")
      "<label for=\"sn-#{id}\" class=\"margin-toggle sidenote-number\"></label>
<input type=\"checkbox\" id=\"sn-#{id}\" class=\"margin-toggle\"/><span class=\"sidenote\">#{@text}</span>"
    end
  end
end

Liquid::Template.register_tag('sidenote', Jekyll::SidenoteTag)

Now all I need to do to create a sidenote is to put in a liquid tag:

{.% sidenote And sidenote text goes here %}

and it gets converted into a proper sidenote. Just like this.

This article is tagged: code ruby blog