Adding CSS and javascript files from extensions

masklinn avatarmasklinn created an issue

It does not seem possible (let alone trivial) to inject CSS or JS content from a sphinx extension, not without serious contorsions anyway:

  • It's easy to do for the project owner by editing conf.py

  • It's specifically supported for theme authors using css_files and script_files

For an extension however I have not found it, the only hook I've managed to dig is connecting to html-page-context and injecting stuff inline in context['metatags'], which feels like a hack and a misuse of the hook. On top of that, it forces the content inline and prevent minimization by sphinx (not that sphinx does minification at the moment, as far as I know) or styles and scripts being injected only where relevant (that is, on documents where the directive or role they're working with was used).

Comments (3)

  1. masklinn

    Not sufficient, these methods only add the provided file paths (prefixed with _static) to the generated pages, they don't publish the files themselves to _static. So the user of the extension would also have to add the file paths to his html_static_path, and thus the extension also has to provide a way to get these paths (and pray it is not a zip/an egg).

  2. masklinn

    So worked around the issue thus: add a sub-directory of the package to the config's html_static_path on the fly and use add_javascript and add_stylesheet to inject those into the document:

    env.config.html_static_path.append(
        os.path.join(os.path.dirname(__file__)),
        'static')
    env.app.add_stylesheet(stylesheet)
    env.app.add_javascript(script)
    

    This works-ish but:

    • depending on the names picked for the static files, it may collide with theme or user-provided file names. It may be possible to alleviate that issue a bit by creating a sub-directory named after the extension
    • it will absolutely definitely not work with zipped modules, since it needs an actual filesystem directory
  3. Log in to comment
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.