jekyll-toc-generator
jekyll-toc-generator adds a table of contents with a post_render hook, so your content files never change.
Open Source Plugin ∙

jekyll-toc-generator

A Jekyll plugin that adds a table of contents to any page with toc: true in its frontmatter, with no Liquid tag in your content.

jekyll-toc-generator adds a table of contents to any Jekyll post or page that has toc: true in its frontmatter. You don’t put a Liquid tag in your content or touch your Markdown files. A post_render hook drops the TOC in before the first heading.

Every other TOC plugin for Jekyll makes you add {% toc %} or something like it inside your actual content. That ties your content to the plugin. If you ever remove the plugin, your posts are left with a broken tag sitting in them. This one stays out of your content completely.

How It Works

After Jekyll renders a document’s Liquid and Markdown, the plugin reads the output HTML, finds every <h2> and <h3> tag, builds a nested <nav> element, and inserts it right before the first <h2>. Your content files stay clean.

Installation

Add to your Gemfile:

gem "jekyll-toc-generator"

Add to plugins: in _config.yml:

plugins:
  - jekyll-toc-generator

Usage

Add toc: true to any post or page frontmatter:

---
title: My Long Post
toc: true
---

That’s all there is to it.

Generated HTML

The TOC uses BEM classes and an ARIA label:

<nav class="toc" aria-label="Table of contents">
  <h2 class="toc__title">Table of Contents</h2>
  <ul class="toc__list">
    <li class="toc__item">
      <a href="#first-heading">First Heading</a>
      <ul class="toc__sublist">
        <li class="toc__item--sub">
          <a href="#sub-heading">Sub Heading</a>
        </li>
      </ul>
    </li>
  </ul>
</nav>

Style it however you like with the .toc, .toc__list, .toc__item, and .toc__sublist classes.

Configuration

toc:
  min_headings: 2        # skip TOC if fewer than N h2s (default: 2)
  title: "Contents"      # TOC heading text (default: "Table of Contents")
  levels: [2, 3]         # heading levels to include (default: [2, 3])

No Extra Dependencies

It’s built entirely on Ruby stdlib regex, so you don’t need Nokogiri or any other gem.

Source

Available on GitHub and RubyGems.

gem install jekyll-toc-generator