automatic toc generation jekyll

Manual creation of tables of contents (TOCs) can be tedious and error-prone for large documentation sites. Automating TOC generation streamlines workflow, keeps content consistent, and improves maintainability.

Challenges with Automatic TOC in Jekyll

  • Jekyll on GitHub Pages restricts plugins for security
  • Liquid itself lacks the ability to parse Markdown headings dynamically
  • Need to rely on JavaScript or safe plugins for TOC generation

Available Methods to Automate TOC Generation

1. Using jekyll-toc Plugin (Locally or on Custom Server)

The jekyll-toc plugin parses headings and inserts TOC automatically. However, it is not supported by default on GitHub Pages, so it requires custom builds.

gem 'jekyll-toc'
# in _config.yml
plugins:
  - jekyll-toc

Once installed, insert TOC in Markdown with:

{% raw %}{% toc %}{% endraw %}

2. Using JavaScript TOC Libraries

Libraries like tocbot generate TOC client-side from headings. This works well with GitHub Pages without plugins.

  • Include tocbot CSS and JS files in your layout
  • Add a container for TOC
  • Initialize tocbot with your desired selectors

Example Setup

<link href="https://unpkg.com/[email protected]/dist/tocbot.css" rel="stylesheet">
<script src="https://unpkg.com/[email protected]/dist/tocbot.min.js"></script>

<nav id="toc" class="toc-container"></nav>

<script>
  tocbot.init({
    tocSelector: '#toc',
    contentSelector: '.post-content',
    headingSelector: 'h2, h3, h4',
    collapseDepth: 6
  });
</script>

3. Using Custom Liquid and JavaScript Hybrid

Combine manual TOC structure in front matter and JavaScript for expanding/collapsing. This method offers more control and works everywhere.

Best Practices for TOC Automation

  • Keep TOC depth reasonable (2-3 levels)
  • Use unique heading IDs for correct linking
  • Make TOC responsive and accessible
  • Test on multiple devices and screen readers

Conclusion

While Jekyll’s native tooling limits full automation of TOC generation on GitHub Pages, combining JavaScript libraries like tocbot or manual Liquid front matter data with scripts provides a practical solution. Choose the method that best fits your project and hosting constraints.

Further Resources