如何在Sphinx autosummary中不新建文件添加toctree层级?
解决Sphinx autosummary层级扩展问题(Module → Section → Bar)
核心思路
不新增文件/文件夹的前提下,通过自定义autosummary模板给模块页面插入Section层级,并配置toctree指向页面内锚点,实现目标层级结构。
步骤1:自定义autosummary模块模板
- 在项目文档目录下创建
_templates/autosummary/文件夹(如果不存在)。 - 从Sphinx安装目录(通常是
site-packages/sphinx/ext/autosummary/templates/autosummary/)复制module.rst到上述自定义目录。 - 修改模板内容,在生成Bar类/函数的区块前添加带锚点的Section标题:
{% block content %} {{ fullname | escape | underline}} .. automodule:: {{ fullname }} {% block functions %} {% if functions %} **{{ _('Functions') }}** .. autosummary:: {% for item in functions %} {{ fullname }}.{{ item }} {% endfor %} {% endif %} {% endblock %} {% block classes %} {% if classes %} <!-- 新增带锚点的Section --> .. _{{ fullname }}-target-section: {{ _('目标Section名称') }} {{ '=' * ( _('目标Section名称') | length ) }} .. autosummary:: {% for item in classes %} {{ fullname }}.{{ item }} {% endfor %} {% endif %} {% endblock %} {% block exceptions %} {% if exceptions %} **{{ _('Exceptions') }}** .. autosummary:: {% for item in exceptions %} {{ fullname }}.{{ item }} {% endfor %} {% endif %} {% endblock %} {% endblock %}
- 用
.. _{{ fullname }}-target-section:创建唯一锚点,避免冲突 - 标题下方的等号长度要和标题一致,确保渲染成Section层级
步骤2:配置toctree指向页面内锚点
在你的主文档(如index.rst)的toctree区块中,直接引用锚点链接:
.. toctree:: :maxdepth: 2 # 方式1:直接用页面+锚点路径 your_module_name#your_module_name-target-section # 方式2:用ref语法更清晰 :ref:`your_module_name-target-section`
步骤3:验证效果
重新执行文档生成命令:
sphinx-build -b html docs/source docs/build
查看toctree中的Section链接是否直接跳转到对应模块页面内的目标章节,层级结构是否符合Module → Section → Bar的要求。
内容的提问来源于stack exchange,提问作者ego-thales
相关产品推荐
相关产品推荐

