简体   繁体   中英

adding custom script to certain docs in sphinx

I have this folder structure for generating docs (html) in sphinx:

doc-root
- static (custom.css, custom.js)
- doc-1 (*.rst)
- doc-2 (*.rst)
- doc-3 (*.rst)
conf.py
index.rst (toctree for doc-1, doc-2 and doc-3)

I'm generating htmls and want to add the custom.js as a script tag only for doc-2.

I tried adding the app.add_javascript('custom.js') in the setup(app) of root conf.py, but sphinx adds the custom.js to all generated htmls.

I added a doc-1/conf.py and added the setup(app), but it never gets called, because I am generating htmls from the root directory using -c option from the root.

Is there a way to achieve this, by making sphinx respect conf.py from its subfolders or by providing logic in the root conf.py?

I have figured a solution:

Add the custom.js to _static/ folder; then create a doc-root/templates/layout.html file with contents:

{% extends "!layout.html" %}

{%- block extrahead %}
<meta name="sourcename" content="{{ sourcename }}" />
{% if "doc-2" in sourcename %}
  <script type="text/javascript" src="./_static/custom.js"></script>
{% endif %}
{% endblock %}

Ensure the src attr points to the correct relative js file. I have added the meta tag just to echo the current doc value. When the sourcename variable contains the doc-2/index.rst.txt value, the script will be added.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM