rbowen / centos / centos.org

Forked from centos/centos.org 3 years ago
Clone

Blame lib/filters/add_toc.rb

e8ec7a
class AddTOCFilter < Nanoc::Filter
e8ec7a
e8ec7a
  identifier :add_toc
e8ec7a
e8ec7a
  def run(content, params={})
e8ec7a
    content.gsub('{{TOC}}') do
e8ec7a
      # Find all top-level sections
e8ec7a
      doc = Nokogiri::HTML(content)
e8ec7a
      headers = doc.xpath('//h2').map do |header|
e8ec7a
        { :title => header.inner_html, :id => header['id'] }
e8ec7a
      end
e8ec7a
e8ec7a
      if headers.empty?
e8ec7a
        next ''
e8ec7a
      end
e8ec7a
e8ec7a
      # Build table of contents
e8ec7a
      res = '
    '
e8ec7a
      headers.each do |header|
e8ec7a
        res << %[
  • #{header[:title]}
  • ]
    e8ec7a
          end
    e8ec7a
          res << ''
    e8ec7a
    e8ec7a
          res
    e8ec7a
        end
    e8ec7a
      end
    e8ec7a
    e8ec7a
    end