require 'nokogiri' module Jekyll class TOC < Liquid::Tag def render context # load HTML into nokogiri html = context.registers[:page]['content'] doc = Nokogiri::HTML(html) # enumerate over all h1-4 headings @els = doc.css("h1, h2, h3, h4") return '
%s
' % [ output_toc ] end def output_toc # empty toc (this check prevents crash) return "" if @els.length == 0 output = '' return output end def el_level el return Integer(el.name[1..]) end end end Liquid::Template.register_tag('toc', Jekyll::TOC)