TOC Menu Fails to Collapse When Hosting _build/html on Webserver

Introduction

When building documentation using Sphinx and deploying the _build/html on a webserver, users may encounter an issue where the table of contents (TOC) menu remains expanded and does not collapse when expected. This article aims to provide a solution to this problem.

Cause of the Issue

The TOC menu collapse functionality is implemented using JavaScript. When the _build/html is hosted on a webserver, the base URL of the page changes from the local file system to the server’s address. As a result, the JavaScript code that handles the TOC collapse fails to execute correctly.

Solution

To resolve this issue, we need to modify the JavaScript code to accommodate the change in base URL. The following steps outline the solution:

  1. Edit layout.html:

Open the layout.html file located in the _templates directory within the Sphinx source code.

  1. Find the TOC JavaScript:

Search for the following code within the <head> section of layout.html:

<script src="{{ pathto('_static/navtree.js', 1) }}" defer></script>
  1. Append the Base URL:

Add the following line below the existing script tag, replacing YOUR_BASE_URL with the actual base URL of your website:

<script>
    window.base_url = 'YOUR_BASE_URL';
</script>
  1. Save and Rebuild:

Save the layout.html file and rebuild the documentation using Sphinx.

Example:

If your website’s base URL is https://example.com/docs/, the modified layout.html will include the following code:

<script src="{{ pathto('_static/navtree.js', 1) }}" defer></script>
<script>
    window.base_url = 'https://example.com/docs/';
</script>

Verification

After rebuilding the documentation and deploying it on the webserver, refresh the page. The TOC menu should now collapse properly.

Conclusion

By appending the base URL to the JavaScript code, the TOC collapse functionality is restored when the documentation is hosted on a webserver. This modification ensures a seamless user experience and allows the TOC menu to behave as intended.

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments