如何在Sphinx-doc中加载外部JavaScript

xxk*_*kkk 1 jinja2 python-sphinx

我从sphinx-doc扩展了基本主题,我注意到基本主题宏中的以下代码块layout.html script

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

这是否意味着我可以html_theme_options在我的内部添加如下内容theme.conf

[options]
script_files = 
Run Code Online (Sandbox Code Playgroud)

在我的内部conf.py,我添加:

html_theme_options = {'script_files': '_static'}
Run Code Online (Sandbox Code Playgroud)

但是,使用此设置,构建完全被搞砸了,并产生了以下垃圾页面:

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>...</head>
  <body>
     -->
   <!-- my js code but is automatically commented out-->
  </body>
</html>
Run Code Online (Sandbox Code Playgroud)

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

Tim*_*pik 5

script_files是模板内部变量。您无法通过设置它html_theme_options(所有主题变量都有theme_前缀,请参见下文)。

Sphinx文档在这里说明如何通过script_files变量直接在模板文件中添加其他脚本。

如果您认为在中定义其他脚本很重要conf.py,请按照以下步骤操作:

  1. 将以下行添加到模板的layout.html,例如endblockDOCTYPE定义的下面:

    {% 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']
    }
    
    Run Code Online (Sandbox Code Playgroud)