You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在sphinx_rtd_theme中实现文档目录的折叠与展开功能

你配置不生效的核心原因是collapse_navigation参数仅控制当前页面所属导航项的子节点折叠,要实现所有根级toctree分组默认折叠,按以下步骤操作即可:

  1. 先升级sphinx_rtd_theme到最新版本,避免旧版本参数不兼容:
pip install --upgrade sphinx-rtd-theme
  1. 修改conf.py中的html_theme_options配置,除了collapse_navigation外,新增navigation_expanded参数设为False,这个参数才是控制导航栏是否默认展开所有层级的开关:
html_theme_options = {
    'collapse_navigation': True,
    'navigation_expanded': False,
    # 不要设置titles_only为True,否则会隐藏加号展开按钮
}
  1. 清理之前的构建缓存后重新生成页面,避免旧缓存导致配置不生效:
make clean && make html

如果以上配置还是不符合预期,还可以通过自定义JS注入强制实现折叠效果:
在你的Sphinx项目的_static目录下新建custom.js文件,写入以下内容:

document.addEventListener('DOMContentLoaded', function() {
    // 匹配所有根级可折叠toctree项
    const navItems = document.querySelectorAll('.toctree-l1.has-children');
    navItems.forEach(item => {
        // 移除默认展开的类名
        item.classList.remove('current');
        item.classList.remove('expanded');
        // 隐藏子层级列表
        const childUl = item.querySelector('ul');
        if(childUl) childUl.style.display = 'none';
    });
});

然后在conf.py中添加配置引入这个自定义JS:

html_static_path = ['_static']
html_js_files = ['custom.js']

重新执行make clean && make html即可生效。

内容的提问来源于stack exchange,提问作者Leo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.17 22:24:09