Class: SectionIDFilter

Inherits:
Nanoc3::Filter
  • Object
show all
Defined in:
lib/filters/section_id.rb

Instance Method Summary collapse

Instance Method Details

#run(content, params = {}) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
# File 'lib/filters/section_id.rb', line 11

def run(content, params={})
  parser = HTMLTokenizer.new(content)

  # Table of Contents: Saved for use in the layout
  toc = ""
  
  # Last level of the ToC seen
  last_toc_level = 0
  
  # Final HTML returned for viewing in the browser
  output = ""

  begin
    # Get a chunk of text, up to the next tag
    output << parser.getText

    # Process the header tags
    next_tag = parser.getNextToken
    if next_tag.kind_of?(HTMLTag)
      case next_tag.tag_name
        when "h1"
           # Assemble the new header
           header_text = parser.getTextAndTags("/h1")
           output << "<h1 id=\"#{header_id(header_text)}\">"
                        
           last_toc_level = 1
        
        when "h2"
          # Assemble the new header
          header_text = parser.getTextAndTags("/h2")
          output << "<h2 id=\"#{header_id(header_text)}\">"
          
          # Add to the Table of Contents
          if last_toc_level != 2 then
            toc << "%ul\n"
          end
          
          toc << "%li\n"
          toc << "  %a{:href => \"##{header_id(header_text)}\"}= \"" << header_text << "\"\n"
                     
          last_toc_level = 2
            
        when "h3"
          # Assemble the new header
          header_text = parser.getTextAndTags("/h3")
          output << "<h3 id=\"#{header_id(header_text)}\">"
          
          # Add to the Table of Contents
          if last_toc_level != 3 then
            toc << "  %ul\n"
          end
          
          toc << "    %li\n"
          toc << "      %a{:href => \"##{header_id(header_text)}\"}= \"" << header_text << "\"\n"
         
          last_toc_level = 3

        when "h4"
          # Assemble the new header
          header_text = parser.getTextAndTags("/h4")
          output << "<h4 id=\"#{header_id(header_text)}\">"
        
        when "h5"
          # Assemble the new header
          header_text = parser.getTextAndTags("/h5")
          output << "<h5 id=\"#{header_id(header_text)}\">"
           
        when "h6"
          # Assemble the new header
          header_text = parser.getTextAndTags("/h6")
          output << "<h6 id=\"#{header_id(header_text)}\">"
        
        else
          output << next_tag.raw         
      end
    end

  end until (parser.peekNextToken.nil?)

  engine = Haml::Engine.new(toc)
  
  @item[:toc] = engine.render
  
  return output
end