如何在Sphinx页面中添加Ace代码编辑器并解决资源加载报错?
解决Sphinx页面添加Ace编辑器的问题
核心问题
你的报错源于本地Ace资源路径配置错误:Sphinx生成HTML后,原RST中的相对路径./src-noconflict/ace.js无法指向root_folder下的资源,导致404加载失败,进而引发ace is not defined错误。此外,你在raw HTML中嵌套了<body>标签,这会和Sphinx生成的页面结构冲突,需要移除。
方案一:使用本地静态资源(推荐)
步骤1:整理静态资源目录
在
root_folder下创建static目录,将整个src-noconflict文件夹复制到static内,最终结构:root_folder static/ src-noconflict/ ace.js theme-monokai.js mode-javascript.js ... content/ folder1/folder2/folder3/folder4/my_page.rst ...修改Sphinx配置文件
conf.py:- 如果
conf.py在root_folder下,添加:html_static_path = ['static'] - 如果
conf.py在content目录下,添加:html_static_path = ['../static']
这会让Sphinx构建时自动将
static目录的资源复制到生成的HTML目录中。- 如果
步骤2:修改RST中的代码
移除多余的<body>标签,将脚本路径改为Sphinx生成后的静态资源绝对路径:
Title ===== .. raw:: html <div id="editor" style="height: 200px; border: 1px solid #ccc;">function foo(items) { var x = "All this is syntax highlighted"; return x; }</div> <script src="/_static/src-noconflict/ace.js" type="text/javascript" charset="utf-8"></script> <script> var editor = ace.edit("editor"); editor.setTheme("ace/theme/monokai"); editor.session.setMode("ace/mode/javascript"); // 可选:设置编辑器高度等样式 editor.setOptions({ maxLines: 10, minLines: 5 }); </script>
步骤3:重新构建文档
执行Sphinx构建命令(根据你的项目调整):
make html # 或者 sphinx-build -b html content build/html
方案二:使用CDN加载(更简单)
无需本地存放Ace文件,直接使用CDN资源,避免路径问题:
Title ===== .. raw:: html <div id="editor" style="height: 200px; border: 1px solid #ccc;">function foo(items) { var x = "All this is syntax highlighted"; return x; }</div> <script src="https://cdn.jsdelivr.net/npm/ace-builds@1.32.0/src-noconflict/ace.js"></script> <script src="https://cdn.jsdelivr.net/npm/ace-builds@1.32.0/src-noconflict/theme-monokai.js"></script> <script src="https://cdn.jsdelivr.net/npm/ace-builds@1.32.0/src-noconflict/mode-javascript.js"></script> <script> var editor = ace.edit("editor"); editor.setTheme("ace/theme/monokai"); editor.session.setMode("ace/mode/javascript"); </script>
直接重新构建文档即可,无需修改静态资源配置。
内容的提问来源于stack exchange,提问作者Cr3
相关产品推荐
相关产品推荐

