Table of Contents for Pelican Posts

Here's a short post to show you how to insert a table of contents (TOC) into posts on a website generated with Pelican. You can see an example of the TOC at the beginning of this post.

Adding a table of contents can be done in three easy steps:

  • Enable the markdown extension in the configuration
  • Add CSS styling to your theme
  • Add the TOC tag to your articles

Enable Markdown Extension

Edit your pelicanconf.py configuration file and add the setting to enable the Markdown TOC extension like this:

MARKDOWN = {
    'extension_configs': {
        # Needed for code syntax highlighting
        'markdown.extensions.codehilite': {
            'css_class': 'highlight'
        },
        'markdown.extensions.extra': {},
        'markdown.extensions.meta': {},
        # This is for enabling the TOC generation
        'markdown.extensions.toc': {
            'title': 'Table of Contents',
        },
    },
    'output_format': 'html5',
}

This code enables the extension and defines the title above the table of contents. You can modify the title if you want.

Define CSS Style

It's not strictly required to add CSS to format the TOC, but with some CSS the TOC looks much more nice. Here's the formatting for my website.

.toc {
    font-size: small;
    display: table;
    width: auto;
}

/* TOC heading in bold */
.toc .toctitle {
    font-weight: bold;
}

/* No bullets for toc list, indentation of nested lists 1em */
.toc ul {
    list-style-type: none;
    padding-left: 1rem;
}

/* Top level list has no indentation */
.toc > ul {
    /* no indentation */
    padding-left: 0;
    margin-top: 0;
}

Add a TOC to your Posts

This is quite simple. Just add the [TOC] tag where you want the table of contents to appear.

LinkedIn logo mail logo