Inject JavaScript based on user configuration¶
If your extension makes use of JavaScript, it can be useful to allow users
to control its behavior using their Sphinx configuration. However, this can
be difficult to do if your JavaScript comes in the form of a static library
(which will not be built with Jinja).
There are two ways to inject variables into the JavaScript space based on user
configuration.
First, you may append _t to the end of any static files included with your
extension. This will cause Sphinx to process these files with the templating
engine, allowing you to embed variables and control behavior.
For example, the following JavaScript structure:
mymodule/
├── _static
│ └── myjsfile.js_t
└── mymodule.py
Will result in the following static file placed in your HTML’s build output:
_build/
└── html
└── _static
└── myjsfile.js
See 静态模板 for more information.
Second, you may use the Sphinx.add_js_file() method without pointing it
to a file. Normally, this method is used to insert a new JavaScript file
into your site. However, if you do not pass a file path, but instead pass
a string to the “body” argument, then this text will be inserted as JavaScript
into your site’s head. This allows you to insert variables into your project’s
JavaScript from Python.
For example, the following code will read in a user-configured value and then
insert this value as a JavaScript variable, which your extension’s JavaScript
code may use:
# This function reads in a variable and inserts it into JavaScript
def add_js_variable(app):
# This is a configuration that you've specified for users in `conf.py`
js_variable = app.config['my_javascript_variable']
js_text = "var my_variable = '%s';" % js_variable
app.add_js_file(None, body=js_text)
# We connect this function to the step after the builder is initialized
def setup(app):
# Tell Sphinx about this configuration variable
app.add_config_value('my_javascript_variable')
# Run the function after the builder is initialized
app.connect('builder-inited', add_js_variable)
As a result, in your theme you can use code that depends on the presence of
this variable. Users can control the variable’s value by defining it in their
conf.py file.
它不是一个可执行的Python文件,而不是:file:配置文件,因为如果共享主题,则会带来不必要的安全风险。