Footnotes

October 07, 2010

So, I wrote my own nanoc filter to do simple footnotes1, roughly in the vain as the wp-footnotes plug-in I had used earlier. The code is relatively simple and generic, so here goes:

class FootnoteFilter < Nanoc3::Filter
  identifier :footnote
  type :text

  def run(content, params={})
    content_add = ""
    i = 0

    newcontent = content

    content.scan(/<footnote>(.*)<\/footnote>/) do |match|
      id = "footnote-#{@item.identifier}-#{i+=1}"
      newcontent =
        newcontent.sub(/<footnote>.*<\/footnote>/,
        "<a href=\"##{id}\" id=\"#{id}-back\"
        class=\"footnote-link\">#{i}</a>")
      content_add +=
        "<li id=\"#{id}\""">#{match}
        <a href=\"##{id}-back\"
        class=\"footnote-backlink\">↖</a></li>"
    end

    if content_add != ""
      content_add =
        "<ol class=\"footnotes\">" +
        content_add +
        "</ol>"
    end

    newcontent + content_add
  end
end

Put that somewhere in your lib/ folder as, say, FootnoteFilter.rb, and reference it in your Rules — for instance:

compile '*' do
  filter :erb
  filter :kramdown
  filter :footnote
  layout 'default'
end

Now, have a footnote2, simply by wrapping the text inside <footnote> tags.

  1. Like this one!

  2. Here’s another!