如何在Sphinx“ toctree”中有条件地包含文件?

oro*_*ome 5 python conditional tableofcontents python-sphinx

我只想在设置了特定标签后才将其中一个文件包含在Sphinx TOC中,但是显而易见的方法失败了:

.. toctree::
   :maxdepth: 5

   index
   core
   utils
   oec
   plotting

   install
   news

   glossary

   .. only:: private_version

      todo
Run Code Online (Sandbox Code Playgroud)

有没有简单的方法可以做到这一点?

Kak*_*ait 4

过去,我需要能够从同一个源文件编译两个文档:公共文档和私有文档。

为了成功,我必须编写自己的插件(您可以在这里找到)。

当我的文件仅包含在私人文档中时,我只需在文件顶部添加以下指令(强制)

.. meta::
    :scope: private_version
Run Code Online (Sandbox Code Playgroud)

public-sample.rst(没什么特别的)

Title
=====

A public content
Run Code Online (Sandbox Code Playgroud)

私人样本.rst

.. meta::
    :scope: private_version

Title
=====

A private content
Run Code Online (Sandbox Code Playgroud)

索引.rst

.. toctree::
    :maxdepth: 3

    public-sample.rst
    private-sample.rst
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,toctree有两个参考,但如果您不使用标签构建,则插件将在编译期间删除private-sample.rstprivate

所以使用

sphinx-build ... -t private_version ...
Run Code Online (Sandbox Code Playgroud)

将生成toctree如下:

  • 公共样本.rst
  • 私人样本.rst

但如果你用

sphinx-build ... -t other ...
Run Code Online (Sandbox Code Playgroud)

或者

sphinx-build ...
Run Code Online (Sandbox Code Playgroud)

将会toctree看起来像

  • 公共样本.rst

我的插件不是 100% 完美,但我只是一小段易于理解的代码,因此您可以根据需要进行编辑:)

了解限制:

局限性:

  • 指令 .. meta:: :scope: 必须放在文件顶部(之前没有行)
  • 指令 .. meta:: :scope: 必须与正则表达式 ^.. meta::\s+:scope: ([a-zA-Z0-9_-]+) 匹配
  • 指令 .. meta:: :scope: 可以管理多个标签,但您可以根据需要轻松更新插件
  • 插件偏离了指令的原始用途metadocutils.sourceforge.net/docs/ref/rst/directives.html#meta