I want to do multiple versions of a documentation, which differ in the sections that are included. To achieve this I would usually use either the only directive or the ifconfig extension. However, I cannot use any of those in combination with the toctree directive.
What I basically want is something like this:
.. toctree::
:maxdepth: 2
intro
strings
datatypes
numeric
.. only:: university
complex
Is there a way to do that?
A very simple solution is to maintain two separate index files under different names. You can specify which index file to use by default in
conf.py
and override it for a special build using-D master_doc=alternate-index
on thesphinx-build
command line.My solution is to place the conditional content in a separate directory 'intern' and using a tag 'internal'.
In conf.py I added the lines
Now when I pass the 'internal' flag on the command line I get all, otherwise everything except the contents in the intern directory.
The tag internal can be used in combination with only.
The ToC contains references to intern/somedoc and they are included or skipped as required. I do get a number of warnings about missing pages but those can be silenced.
As far as I know there is no way to do what you would like. I have been struggling with the same issue, see https://github.com/sphinx-doc/sphinx/issues/1717.
The reason is that Sphinx process all lines contained in a toctree node as pure text.
I see two alternatives:
you can extend the toctree including an option that contains the expression to be evaluated
and then you customize the doctree resolve event.
you can use text substitutions on the raw text defining your own tags. you can do that implementing an event handler for the source-read event. For instance
$$condition$$
could contain the condition to be evaluated, while$$$
the end of the block, i.e.Depending on
mycondition
, you can remove the following block lines.Number 3 is quite simple, while to me number 2 is the most elegant.
My previous answer fails if you have hierarchies of table of contents so I wrote a simple
toctree-filt
directive that is able to filter entries based on a prefix to the entry. For example, given atoctree-filt
directive likeand setting the exclusion list to
['draft','erik']
will result in an effective toctree that looks likeAdd the following lines to your
conf.py
:Put the following code in
/sphinx_ext
next to your/source
directory:Now just change your existing
toctree
directives totoctree-filt
and you are good to roll. Note that Sphinx will post errors because it will find files that are not included in the document. Not sure how to fix that.