HomeArticles

Jekyll table of contents per page

Stefan Baumgartner

Written by @ddprrt

More on Jekyll

This filter creates a table of contents list based on all h2 tags that are on your site.

module TocFilter
def toc(input)
output = "<ul class=\"toc\">"
input.scan(/<(h2)(?:>|\s+(.*?)>)([^<]*)<\/\1\s*>/mi).each do |entry|
id = (entry[1][/^id=(['"])(.*)\1$/, 2] rescue nil)
title = entry[2].gsub(/<(\w*).*?>(.*?)<\/\1\s*>/m, '\2').strip
if id
output << %{<li><a href="##{id}">#{title}</a></li>}
else
output << %{<li>#{title}</li>}
end
end
output << '</ul>'
output
end
end
Liquid::Template.register_filter(TocFilter)

Use it with


{{ content | toc }}

Anywhere in your layouts.

More articles on Jekyll

Stay up to date!

3-4 updates per month, no tracking, spam-free, hand-crafted. Our newsletter gives you links, updates on fettblog.eu, conference talks, coding soundtracks, and much more.