javascriptpythonpython-sphinx

Adding a JavaScript script tag some place so that it works for every file in Sphinx


I am using Sphinx to write some notes. I am using the Mathjax extension for Math in the notes. The default size of the math is little larger than I would like. On the Mathjax page I found that I can change that size by adding the following script to the HTML file.

MathJax.Hub.Config({
  "HTML-CSS": {scale: 90}
});

So, I tried by adding the following in a .rst file:

.. raw:: html

    <script type="text/javascript" >
        MathJax.Hub.Config({
            "HTML-CSS": {
                scale: 90
            }
        });
    </script>

==========
Objective
==========

To change math size \\( \\alpha \\).

The above works great for the math in that specific .rst file. But I want to do this for many different .rst files that are all part of the same Sphinx document. Is it possible to do this without adding the above script to every .rst file?


Solution

  • This can be done with a template:

    1. Create a folder called templates in the Sphinx project directory.

    2. In conf.py, add

      templates_path = ["templates"]
      
    3. In the templates directory, create a file called layout.html with the following contents:

       {% extends "!layout.html" %}
      
       {%- block extrahead %} 
        <script type="text/javascript">
              MathJax.Hub.Config({
                  "HTML-CSS": {
                      scale: 90
                  }
              });
         </script>      
       {% endblock %}
      

    The <script> element will be included in the <head> of every generated HTML page.

    The extrahead template block is empty by default. See the Sphinx templating documentation for details.