如果目录存在层级关系,我的先前回答可能会失败,因此我编写了一个简单的toctree-filt
指令,它能够根据条目前缀过滤条目。例如,给定一个类似以下的toctree-filt
指令:
.. toctree-filt::
:maxdepth: 1
user-manual
:internal:supervisor-api
:draft:new-feature
:erik:erik-maths
api
将排除列表设置为['draft','erik']
将会得到如下有效的目录树:
.. toctree-filt::
:maxdepth: 1
user-manual
supervisor-api
api
conf.py
文件中:
sys.path.append(os.path.abspath('../sphinx-ext/'))
extensions = ['toctree_filter']
toc_filter_exclude = ['draft','erik']
将以下代码放置在您的/source
目录旁边的/sphinx_ext
中:
import re
from sphinx.directives.other import TocTree
def setup(app):
app.add_config_value('toc_filter_exclude', [], 'html')
app.add_directive('toctree-filt', TocTreeFilt)
return {'version': '1.0.0'}
class TocTreeFilt(TocTree):
"""
Directive to notify Sphinx about the hierarchical structure of the docs,
and to include a table-of-contents like tree in the current document. This
version filters the entries based on a list of prefixes. We simply filter
the content of the directive and call the super's version of run. The
list of exclusions is stored in the **toc_filter_exclusion** list. Any
table of content entry prefixed by one of these strings will be excluded.
If `toc_filter_exclusion=['secret','draft']` then all toc entries of the
form `:secret:ultra-api` or `:draft:new-features` will be excuded from
the final table of contents. Entries without a prefix are always included.
"""
hasPat = re.compile('^\s*:(.+):(.+)$')
# Remove any entries in the content that we dont want and strip
# out any filter prefixes that we want but obviously don't want the
# prefix to mess up the file name.
def filter_entries(self, entries):
excl = self.state.document.settings.env.config.toc_filter_exclude
filtered = []
for e in entries:
m = self.hasPat.match(e)
if m != None:
if not m.groups()[0] in excl:
filtered.append(m.groups()[1])
else:
filtered.append(e)
return filtered
def run(self):
# Remove all TOC entries that should not be on display
self.content = self.filter_entries(self.content)
return super().run()
现在只需将现有的toctree
指令更改为toctree-filt
,您就可以开始使用了。请注意,Sphinx会报错,因为它会找到未包含在文档中的文件。不确定如何修复此问题。
.. only::
指令来解决这个问题。 - Kdawg一个非常简单的解决方案是维护两个不同名称的独立索引文件。您可以在conf.py
中指定默认使用哪个索引文件,并通过在sphinx-build
命令行上使用-D master_doc=alternate-index
来覆盖特殊构建。
you can extend the toctree including an option that contains the expression to be evaluated
.. toctree:
:condition: expression
file1
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
$$$
根据mycondition
的不同,您可以删除以下代码块。
第三个选项非常简单,而对我来说第二个选项最为优雅。
if tags.has('internal'):
exclude_patters = ['_build']
else:
exclude_patterns = ['_build', 'intern*']