Skip to content

Adding CSS and javascript files from extensions #11173

@jdillard

Description

@jdillard

Describe the bug

Considering this a bug in the docs, i.e. missing information, assuming this is possible in a recommended fashion. Or a feature request to make a recommended fashion possible if there currently is none.

Basically reviving this old thread #1379, as it doesn't seem like there was a clear answer at the end. Given that this is a common enough requirement in extensions, I think it should be mentioned in the docs.

I looked at how some of the more popular extensions handle this and they seem to use the not recommended method of modifying app.config.html_static_path.

It was recommended to do the following:

from os import path
from sphinx.util.fileutil import copy_asset

def copy_asset_files(app, exc):
  if app.builder.format == 'html' and not exc:
        custom_file = str(Path(__file__).parent.joinpath("static", "example.js").absolute())
        static_dir = path.join(app.builder.outdir, '_static')
        copy_asset_file(custom_file, static_dir)

def setup(app):
  app.connect('build-finished', copy_asset_files)

which works for copying the file into the _static folder, but it isn't clear how to add the necessary tags to the HTML, like add_js_file does:

<script src="_static/example.js"></script>

So, when you follow the recommended method of copying the files, what is the recommended method for adding the appropriate tags to the HTML?

Edit: I solved my own issue using html_js_files as taken from #10608:

def setup_config(app, exception):
  html_js_files = getattr(app.config, "html_js_files", [])
  html_js_files.append('example.js')
  app.config.html_js_files = html_js_files

def setup(app):
  app.connect('config-inited', setup_config)

If that is the recommended method, I can try to work on some example extension docs for adding JS/CSS if desired.

How to Reproduce

Try to figure out how to add JS/CSS in an extension using the Writing Sphinx Extensions documentation.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions