gpt4 book ai didi

conditional-statements - 狮身人面像中的有条件toctree

转载 作者:行者123 更新时间:2023-12-04 10:53:35 29 4
gpt4 key购买 nike

我想做一个文档的多个版本,这些版本在所包含的部分中有所不同。为此,我通常使用only指令或ifconfig扩展名。但是,我不能将这些与toctree指令一起使用。

我基本上想要的是这样的:

.. toctree::
:maxdepth: 2

intro
strings
datatypes
numeric
.. only:: university
complex

有没有办法做到这一点?

最佳答案

如果您具有目录的层次结构,我的上一个答案将失败,因此我编写了一个简单的toctree-filt指令,该指令能够基于条目的前缀来过滤条目。例如,给定一个toctree-filt指令,例如

.. toctree-filt::
:maxdepth: 1

user-manual
:internal:supervisor-api
:draft:new-feature
:erik:erik-maths
api

并将排除列表设置为 ['draft','erik']将导致
看起来像有效的toctree
.. 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']

将以下代码放在 /sphinx_ext目录旁边的 /source中:

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将发布错误,因为它将查找文档中未包含的文件。不确定如何解决。

关于conditional-statements - 狮身人面像中的有条件toctree,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15001888/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com