javascriptjinja2python-sphinx

How to load external JavaScript in Sphinx?


I'm extending the basic theme from sphinx-doc and I notice the following code chunk inside basic theme layout.html script macro

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

Does that mean I can add a html_theme_options like the following inside my theme.conf:

[options]
script_files = 

and inside my conf.py, I add:

html_theme_options = {'script_files': '_static'}

However, with this set, the build is totally messed up and produced junk pages like:

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

Which part goes wrong? What should I do in order to load my own customized JavaScript?


Solution

  • script_files is a template-internal variable. You cannot set it via html_theme_options (all theme variables have theme_as a prefix, see below).

    The Sphinx docs explain here how to add additional scripts directly in the template files, via the script_files variable.

    In case you regard it as important to define the additional scripts in your conf.py, proceed as follows:

    1. Add the following line to your template's layout.html, for example below the endblock of the DOCTYPE definition:

    {% set script_files = script_files + theme_extra_scripts %}

    1. Define the theme variable extra_scripts and its default value in theme.conf:

    extra_scripts = []

    1. Override the variable in conf.py:

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