Skip to content

Commit fc66a22

Browse files
committed
Doc: render version/language selector on Read the Docs
Integrate the new Read the Docs Addons JavaScript into the Python Docs Sphinx theme to render versions and languages selector nicely. References: * Discord thread: https://discord.com/channels/935215565872693329/1159601953265942589 * Implementation of Addons JavaScript `CustomEvent`: readthedocs/addons#64 * Conversation about using Read the Docs: python/docs-community#5
1 parent f6cdc6b commit fc66a22

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

Doc/tools/templates/layout.html

+55
Original file line numberDiff line numberDiff line change
@@ -41,4 +41,59 @@
4141
{{ "}" }}
4242
</style>
4343
{{ super() }}
44+
45+
<meta name="readthedocs-addons-api-version" content="0">
46+
<script type="text/javascript">
47+
function onSwitch(event) {
48+
const option = event.target.selectedIndex;
49+
const item = event.target.options[option];
50+
window.location.href = item.dataset.url;
51+
}
52+
53+
document.addEventListener("readthedocs-addons-data-ready", function(event) {
54+
const config = event.detail;
55+
const languageMapping = {
56+
en: "English",
57+
es: "Spanish",
58+
// ...
59+
}
60+
61+
// TODO: add `selected="selected"` to option
62+
const versionSelect = `
63+
<select id="version_select">
64+
${ config.addons.flyout.versions.map(
65+
(version) => `
66+
<option
67+
value="${ version.slug }"
68+
${ config.versions.current.slug === version.slug ? 'selected="selected"' : '' }
69+
data-url="${ version.url }">
70+
${ version.slug }
71+
</option>`
72+
).join("\n") }
73+
</select>
74+
`;
75+
76+
const languageSelect = `
77+
<select id="language_select">
78+
${ config.addons.flyout.translations.map(
79+
(translation) => `
80+
<option
81+
value="${ translation.slug }"
82+
${ config.projects.current.language.code === translation.slug ? 'selected="selected"' : '' }
83+
data-url="${ translation.url }">
84+
${ languageMapping[translation.slug] }
85+
</option>`
86+
).join("\n") }
87+
</select>
88+
`;
89+
90+
const selectVersionElement = document.querySelector("li.switchers div.version_switcher_placeholder");
91+
selectVersionElement.innerHTML = versionSelect;
92+
document.querySelector("li.switchers div.version_switcher_placeholder").addEventListener("change", onSwitch);
93+
94+
const selectLanguageElement = document.querySelector("li.switchers div.language_switcher_placeholder");
95+
selectLanguageElement.innerHTML = languageSelect;
96+
document.querySelector("li.switchers div.language_switcher_placeholder select").addEventListener("change", onSwitch);
97+
});
98+
</script>
4499
{% endblock %}

0 commit comments

Comments
 (0)