Commit 4110cb88 authored by Tobias Schmidt's avatar Tobias Schmidt

Add table of contents filter

parent ccc3d974
...@@ -46,6 +46,7 @@ compile '*' do ...@@ -46,6 +46,7 @@ compile '*' do
filter :bootstrappify filter :bootstrappify
filter :admonition filter :admonition
filter :colorize_syntax, :default_colorizer => :pygmentsrb filter :colorize_syntax, :default_colorizer => :pygmentsrb
filter :toc, style: item[:toc]
if item[:kind] == 'article' if item[:kind] == 'article'
layout 'blog' layout 'blog'
else else
......
--- ---
title: FAQ title: FAQ
sort_rank: 5 sort_rank: 5
toc: full-width
--- ---
# Frequently Asked Questions # Frequently Asked Questions
......
# encoding: utf-8
require 'nokogiri'
class TocFilter < ::Nanoc::Filter
identifier :toc
# Number of items required to render a table of contents.
TOC_MINIMUM = 2
def run(content, params={})
doc = Nokogiri::HTML(content)
titles = doc.xpath('//h1')
headers = doc.xpath('//h2|//h3')
if titles.empty? || headers.length < TOC_MINIMUM
return content
end
style = params[:style] || 'right'
items = headers.map do |header|
title = header.inner_html.sub(/^(.*)<a .*$/, '\1')
{ :level => header.name, :title => title, :id => header['id'] }
end
titles.first.after(%(<div class="toc toc-#{style}">#{toc(items)}</div>))
doc.to_s
end
def toc(items)
return '' if items.empty?
level = ''
table = []
items.each do |item|
if item[:level] > level
table << '<ul>'
elsif item[:level] < level
table << '</ul>'
end
level = item[:level]
table << %(<li><a href="##{item[:id]}">#{item[:title]}</a></li>)
end
table << '</ul>'
table.join('')
end
end
...@@ -201,6 +201,27 @@ a.sc-logo img { ...@@ -201,6 +201,27 @@ a.sc-logo img {
display: block; display: block;
} }
.toc {
padding: 1em;
background-color: #eee;
}
.toc-right {
float: right;
width: 40%;
margin: 0 0 0.5em 0.5em;
}
.toc ul {
padding: 0 0 0 1.5em;
margin: 0;
}
.toc a code {
color: #337ab7;
background-color: transparent;
}
pre { pre {
font-family: "Courier New", Monaco, Menlo, Consolas, monospace; font-family: "Courier New", Monaco, Menlo, Consolas, monospace;
background-color: #444; background-color: #444;
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment