Skip to content

Commit e5782be

Browse files
committed
Fix language redirection with a non-empty base URL
1 parent d6553f7 commit e5782be

File tree

3 files changed

+27
-3
lines changed

3 files changed

+27
-3
lines changed

src/main.rs

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,13 @@ fn setup_handlebars() -> anyhow::Result<Handlebars<'static>> {
6868
}
6969

7070
fn main() -> anyhow::Result<()> {
71+
// It is possible to set a base URL for the web.
72+
// This should set to the path under which the web is hosted.
73+
// For example, if the web is hosted at https://foo.bar/rust-web/, then BASE_URL should be set
74+
// to "/rust-web".
75+
// This is mainly useful to host the website e.g. on GitHub pages without a custom CNAME.
7176
let base_url = std::env::var("BASE_URL").unwrap_or_else(|_| "".to_string());
77+
assert!(base_url.is_empty() || base_url.starts_with("/"));
7278
let base_url = BaseUrl::new(&base_url);
7379

7480
let rust_version = fetch_rust_version()?;

static/scripts/languages.js

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,13 +12,26 @@ function langChange() {
1212
} else {
1313
lang = `/${lang}`;
1414
}
15+
16+
// Base URL of the web, without a leading slash.
17+
// For example "" or "/foo/bar".
18+
let base_url = window.RUST_BASE_URL;
19+
20+
// If we have a path like /foo/bar/<lang>/<page>/<subpage>, we want to extract only
21+
// /<page>/<subpage>
1522
let path = window.location.pathname;
23+
// Remove /foo/bar
24+
if (path.startsWith(base_url)) {
25+
path = path.slice(base_url.length);
26+
}
27+
// Remove /<lang>
1628
if (current_lang != "en-US") {
17-
path = `/${window.location.pathname.split('/').slice(2).join('/')}`;
29+
path = path.slice(current_lang.length + 1); // +1 for leading /
1830
}
19-
window.location = `${lang}${path}`;
31+
32+
// Now reconstruct back /foo/bar
33+
window.location = `${base_url}${lang}${path}`;
2034
}
2135

2236
nav_dropdown.onchange = langChange;
2337
footer_dropdown.onchange = langChange;
24-
// TODO: language redirect

templates/components/layout.html.hbs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,11 @@
5252
<link rel="alternate" href="https://www.rust-lang.org/" hreflang="x-default">
5353
{{/if}}
5454

55+
<script type="text/javascript">
56+
{{!-- Pass the (untranslated) base URL path to languages.js --}}
57+
window.RUST_BASE_URL = "{{baseurl_assets}}";
58+
</script>
59+
5560
<!-- Custom Highlight pack with: Rust, Markdown, TOML, Bash, JSON, YAML,
5661
and plaintext. -->
5762
<script src="{{baseurl_assets}}/static/scripts/highlight.pack.js" defer></script>

0 commit comments

Comments
 (0)