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

如何在Sphinx页面中添加Ace代码编辑器并解决资源加载报错?

解决Sphinx页面添加Ace编辑器的问题

核心问题

你的报错源于本地Ace资源路径配置错误:Sphinx生成HTML后,原RST中的相对路径./src-noconflict/ace.js无法指向root_folder下的资源,导致404加载失败,进而引发ace is not defined错误。此外,你在raw HTML中嵌套了<body>标签,这会和Sphinx生成的页面结构冲突,需要移除。

方案一:使用本地静态资源(推荐)

步骤1:整理静态资源目录

  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
       ...
    
  2. 修改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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 20:22:49