Module: Jekyll::Filters::Content
- Defined in:
- lib/jekyll/filters/content.rb
Constant Summary collapse
- HEADINGS =
'h1,h2,h3,h4,h5,h6'
Instance Method Summary collapse
-
#canonicalize_headings(input, prefix = nil) ⇒ String
Add id attribute to all headings with an optional prefix.
-
#table_of_contents(input, max_level = 2, prefix = nil) ⇒ Hash
Extracts a table of contents from HTML up to a certain headings level.
Instance Method Details
#canonicalize_headings(input, prefix = nil) ⇒ String
Add id attribute to all headings with an optional prefix. It also creates a table of contents with unique IDs.
It doesn’t change pre-existing IDs.
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 |
# File 'lib/jekyll/filters/content.rb', line 18 def canonicalize_headings(input, prefix = nil) @@canonicalize_headings ||= {} @@canonicalize_headings[input.hash] ||= begin require 'nokogiri' toc = toc(input) html_fragment(input).tap do |html| html.css(HEADINGS).each do |h| id = h['id'] unless id slug = ::Jekyll::Utils.slugify(h.text, mode: 'pretty') id = unique_id(slug, prefix, toc) h['id'] = id end toc[id] = { 'level' => h.name[1].to_i, 'title' => h.text, 'id' => id } end end.to_s end end |
#table_of_contents(input, max_level = 2, prefix = nil) ⇒ Hash
Extracts a table of contents from HTML up to a certain headings level.
It returns an array of hashes with title, level and id.
68 69 70 71 72 73 74 |
# File 'lib/jekyll/filters/content.rb', line 68 def table_of_contents(input, max_level = 2, prefix = nil) canonicalize_headings(input, prefix) toc(input).select do |_id, item| item['level'] <= max_level end.values end |