Adds a Table of Contents to a Markdown document.
This extension is included with the Markdown library since version 2.0.
Place a marker in the document where you would like the table of contents to
appear. Then, a nested list of all the headers in the document will replace the
marker. The marker defaults to [TOC]
so the following document:
[TOC]
# Header 1
## Header 2
would generate the following output:
<div class="toc">
<ul>
<li><a href="#header-1">Header 1</a></li>
<ul>
<li><a href="#header-2">Header 2</a></li>
</ul>
</ul>
</div>
<h1 id="header-1">Header 1</h1>
<h1 id="header-2">Header 2</h1>
From the Python interpreter:
>>> html = markdown.markdown(some_text, extensions=['toc'])
The following options are provided to configure the output:
[TOC]
.slugify
method. The callable must accept one argument which
contains the text content of the header and return a string which will be
used as the anchor text.<div>
. Defaults to None
.True
to have the headers link to themselves.
Default is False
.If a 'marker' is not found in the document, then the toc is available as an attribute of the Markdown class. This allows one to insert the toc elsewhere in their page template. For example:
>>> text = '''
# Header 1
## Header 2
'''
>>> md = markdown.Markdown(extensions=['toc'])
>>> html = md.convert(text)
>>> render_some_template(context={'body': html, 'toc': md.toc})