69

How to include a local table of contents into Sphinx doc?

I tried

.. toc:: 

But that doesn't seem to have any effect: nothing is inserted in the document.

Basically I need links to the sections in the current page to be placed at a certain location of each page.

Is this possible?

bad_coder
  • 11,289
  • 20
  • 44
  • 72
Edy Bourne
  • 5,679
  • 13
  • 53
  • 101

2 Answers2

94

I'm not 100% sure this is what you're looking for, but the .. contents:: directive may help. By default, it'll give you the headings for the whole page, wherever you put the directive. With :local: specified, it will generate a local TOC for the headings below where you put the directive (handy for sub-section tocs).

.. contents:: Table of Contents
    :depth: 3

More details here: http://docutils.sourceforge.net/docs/ref/rst/directives.html#table-of-contents

user5994461
  • 5,301
  • 1
  • 36
  • 57
morric
  • 1,189
  • 1
  • 13
  • 17
  • 41
    `.. contents:: :local:` is the magic juice. When omitting the `:local:` flag, the Table of Contents is uselessly prepended by a link to the document heading. Moreover, all other headings are subheadings of the document heading and hence uselessly indented one level deeper than they otherwise should be. In short, `:local:` is all but mandatory for most use cases. (_I really wish `:local:` were the default, frankly._) – Cecil Curry Aug 14 '16 at 05:40
  • 1
    Does the `:local:` keyword still works? I can't make it function on recent version of sphinx, it seems to only work under H1 title, but not within sections. – cglacet Oct 29 '20 at 02:45
  • As far as I know, yes. I've got a test with it running under H2 in Sphinx 3.5.2. – morric Mar 09 '21 at 09:08
10

I had more luck with:

.. contents:: Table of Contents
   :depth: 1
   :local:
   :backlinks: none

The backlinks gets rid of the annoying links back from the headings to the toc.

isparks
  • 136
  • 1
  • 2