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

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.

Examples:

Render content with unique IDs

{{ content | canonicalize_headings }}

Parameters:

  • input (String)

    HTML string

  • prefix (nil, String) (defaults to: nil)

    Prefix IDs with this

Returns:

  • (String)


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.

Examples:

Create a table of contents

{% assign toc = content | table_of_contents: 2 %}

{% unless toc == empty %}
  {% for item in toc %}
    {% assign heading = "h" | append: item.level %}
    <{{ heading }}>
      <a href="#{{ item.id }}">
        {{ item.title }}
      </a>
    </{{ heading }}>
  {% endfor %}
{% endunless %}

Parameters:

  • input (String)
  • max_level (Integer) (defaults to: 2)

    All headings up to this level

  • prefix (String, nil) (defaults to: nil)

    Prefix

Returns:

  • (Hash)


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