如何在 sphinx-doc 中加载外部 javascript

How to load external javascript in sphinx-doc

我正在扩展 basic theme from sphinx-doc 并且我注意到基本主题中的以下代码块 layout.html script

{%- for scriptfile in script_files %}
<script type="text/javascript" src="{{ pathto(scriptfile, 1) }}"></script>
{%- endfor %}

这是否意味着我可以在 theme.conf:

中添加如下所示的 html_theme_options
[options]
script_files = 

在我的 conf.py 中,我添加:

html_theme_options = {'script_files': '_static'}

然而,对于这个集合,构建完全混乱并产生垃圾页面,如:

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>...</head>
  <body>
     -->
   <!-- my js code but is automatically commented out-->
  </body>
</html>

哪一部分出了问题?我应该怎么做才能加载我自己定制的 javascript?非常感谢!

script_files 是模板内部变量。您不能通过 html_theme_options 设置它(所有主题变量都有 theme_ 作为前缀,见下文)。

Sphinx 文档解释了 here 如何通过 script_files 变量直接在模板文件中添加其他脚本。

如果您认为在 conf.py 中定义附加脚本很重要,请执行以下操作:

  1. 将以下行添加到模板的 layout.html,例如在 DOCTYPE 定义的 endblock 下方:

    {% set script_files = script_files + theme_extra_scripts %}

  2. 定义主题变量extra_scripts及其默认值theme.conf:

    extra_scripts = []

  3. 覆盖conf.py中的变量:

    html_theme_options = {
       'extra_scripts': ['_static/test.js']
    }