Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I link to a page section in a sphinx toctree

I have a .. toctree as part of a sphinx page, which includes relative links to other rst files in my package. How can I include a link to a subsection of a given page, rather than the full page itself?

I took a stab at

.. toctree::

   page#section

But that didn't work. Any help is great.

like image 491
Duncan Macleod Avatar asked Oct 30 '13 15:10

Duncan Macleod


2 Answers

After much hackery, I've come to the following solution, but I should first state that my goal was to:

  1. have the heading NOT appear in the content body
  2. have the heading appear in the TOC

So basically linking from the TOC to an arbitrary but invisible part of a document.

I needed this in order to be able to link to methods in some source code documentation rendered with Sphinxcontrib PHPDomain - these methods generate section links of their own, but do not get added into the TOC by default.

Step 1:

At the top of your RST file which needs this linking functionality, add a new role as such:

.. role:: hidden
   :class: hidden

Step 2:

Somewhere in the content, use this role as such:

:hidden:`My Arbitrary Location`
"""""""""""""""""""""""""""""""

Step 3:

Add new CSS to the project (usually done by adding a CSS file into _static, or defining a style sheet or something like that - see this):

.rst-content .hidden {
    display: none;
}

nav .hidden {
    display: unset;
}

This forces the heading to be hidden in the content, but shown in the TOC.

Then, reuse the role as necessary in other documents.


Note that if your goal is to link to arbitrary locations in the document and still have the headings show up in the content, just change the CSS to style the headings to your liking rather than hide them.

like image 186
Swader Avatar answered Nov 14 '22 16:11

Swader


When creating the ToC, Sphinx is including all headings and subheadings of referenced files within the configured tree depth. So you can simply not start the page with a heading and insert the heading at the point you want the ToC to point to, e.g.:

.. _my-rst-file:
**You can use bold print here if you want. This will not appear in the ToC**
.. rubric:: Or the "rubric" directive

And here some more text, normal font weight.

Here comes the heading that will appear in the ToC
""""""""""""""""""""""""""""""""""""""""""""""""""
And so on...

You need to include the page reference in the ToC as usual. So in the ToC, you have:

.. toctree::

   my_rst_file

In our example, the build result (HTML, PDF, whatever) will only have a reference to Here comes the heading that will appear in the ToCin the ToC.

like image 43
Timotheus.Kampik Avatar answered Nov 14 '22 15:11

Timotheus.Kampik