Skip to content

Commit 99f9b1c

Browse files
drammockdavidism
andauthored
fix URLs for dirhtml builds (#1699)
* fix URLs for dirhtml builds Co-authored-by: David Lord <[email protected]> * Update src/pydata_sphinx_theme/__init__.py --------- Co-authored-by: David Lord <[email protected]>
1 parent b8a388e commit 99f9b1c

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

src/pydata_sphinx_theme/__init__.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
import requests
1010
from requests.exceptions import ConnectionError, HTTPError, RetryError
1111
from sphinx.application import Sphinx
12+
from sphinx.builders.dirhtml import DirectoryHTMLBuilder
1213
from sphinx.errors import ExtensionError
1314

1415
from . import edit_this_page, logo, pygment, short_link, toctree, translator, utils
@@ -215,6 +216,30 @@ def update_and_remove_templates(
215216
context["theme_version"] = __version__
216217

217218

219+
def _fix_canonical_url(
220+
app: Sphinx, pagename: str, templatename: str, context: dict, doctree
221+
) -> None:
222+
"""Fix the canonical URL when using the dirhtml builder.
223+
224+
Sphinx builds a canonical URL if ``html_baseurl`` config is set. However,
225+
it builds a URL ending with ".html" when using the dirhtml builder, which is
226+
incorrect. Detect this and generate the correct URL for each page.
227+
228+
Workaround for https://github.com/sphinx-doc/sphinx/issues/9730; can be removed
229+
when that is fixed, released, and available in our minimum supported Sphinx version.
230+
"""
231+
if (
232+
not app.config.html_baseurl
233+
or not isinstance(app.builder, DirectoryHTMLBuilder)
234+
or not context["pageurl"]
235+
or not context["pageurl"].endswith(".html")
236+
):
237+
return
238+
239+
target = app.builder.get_target_uri(pagename)
240+
context["pageurl"] = app.config.html_baseurl + target
241+
242+
218243
def setup(app: Sphinx) -> Dict[str, str]:
219244
"""Setup the Sphinx application."""
220245
here = Path(__file__).parent.resolve()
@@ -226,6 +251,7 @@ def setup(app: Sphinx) -> Dict[str, str]:
226251

227252
app.connect("builder-inited", translator.setup_translators)
228253
app.connect("builder-inited", update_config)
254+
app.connect("html-page-context", _fix_canonical_url)
229255
app.connect("html-page-context", edit_this_page.setup_edit_url)
230256
app.connect("html-page-context", toctree.add_toctree_functions)
231257
app.connect("html-page-context", update_and_remove_templates)

0 commit comments

Comments
 (0)