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 ifcon
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
.. toctree:
:condition: expression
file1
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.
.. toctree:
file1
$$mycondition$$
file2
$$$
Depending on mycondition, you can remove the following block lines.
Number 3 is quite simple, while to me number 2 is the most elegant.