Conditionally add assets (JS and CSS) to your Sphinx build.
This package allows you to choose certain pages on which to load conditional assets, rather than forcing you to load assets for all pages. This allows you to avoid loading scripts and CSS on pages that do not need them. It is meant primarily for Sphinx developers, but can be used as a part of any Sphinx build.
sphinx-conditional-asset run the following command:
pip install git+https://executablebooks/sphinx-conditional-asset
and activate the extension via
extensions = [ ... "sphinx_conditional_asset", ]
This package adds two new methods to the instance of
is provided by
app.add_css_file_conditional. They take the same arguments as
app.add_css_file, along with an additional
condition argument: takes a function that accepts the same arguments as the
html-page-context Sphinx event.
When each page is loaded, the function will be called with the
arguments. If it returns
True then the asset will be loaded onto the page.
For example, let’s say we only wanted to load
thebe on pages that start with
thebe_. To do so, we’d add this to our
def only_on_some_pages(app, pagename, templatename, context, doctree): if pagename.startswith("thebe_"): return True def setup(app): app.add_js_file_conditional( "https://unpkg.com/thebelab@latest/lib/index.js", only_on_some_pages )
Here’s an example that checks for an
admonition node in the page’s doctree:
from sphinx_theme import ThebeButtonNode def only_when_node_present(app, pagename, templatename, context, doctree): if doctree.traverse(ThebeButtonNode): return True def setup(app): app.add_js_file_conditional( "https://unpkg.com/thebelab@latest/lib/index.js", only_when_node_present )