Skip to content

Commit

Permalink
feat(lang): ✨ dynamically set language of page
Browse files Browse the repository at this point in the history
  • Loading branch information
Timothy-Liuxf committed May 16, 2024
1 parent 611c5a3 commit f12d519
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 25 deletions.
2 changes: 1 addition & 1 deletion 404.html
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
<!DOCTYPE html>
<html lang="{{ site.lang | default: " en-US" }}">
<html lang="en-US">

<head>
<meta charset='utf-8'>
Expand Down
52 changes: 28 additions & 24 deletions _layouts/default.html
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
<!DOCTYPE html>
<html lang="{{ site.lang | default: " en-US" }}">
<html>

<head>
<meta charset='utf-8'>
Expand Down Expand Up @@ -49,6 +49,31 @@
background-color: black;
}
</style>
<script type="text/javascript">
const current_url = window.location.href;
const paths = current_url.split('/');
const pattern = /^(zh-CN|zh-TW|en-US|fr-FR)$/;
let lang_index = -1;
for (let i = 0; i < paths.length; ++i) {
if (pattern.test(paths[i])) {
lang_index = i;
break;
}
}
document.documentElement.lang = lang_index !== -1 ? paths[lang_index] : 'en-US';

const returnToBackPage = () => {
if (lang_index !== -1) {
if (lang_index + 2 === paths.length) {
window.location.href = paths.slice(0, lang_index).join('/') + '/';
} else {
window.location.href = paths.slice(0, lang_index + 1).join('/') + '/';
}
} else {
window.location.href = paths.slice(0, 4).join('/') + '/'
}
};
</script>
{% include head-custom.html %}

{% seo %}
Expand Down Expand Up @@ -90,20 +115,11 @@ <h2>{{ site.description | default: site.github.project_tagline }}</h2>
</option>
</select>
<script>
const current_url = window.location.href;
const paths = current_url.split('/');
const pattern = /^(zh-CN|zh-TW|en-US|fr-FR)$/;
let lang_index = -1;
document.getElementById("select-lang").value = 'en-US';
for (let i = 0; i < paths.length; ++i) {
if (pattern.test(paths[i])) {
document.getElementById("select-lang").value = paths[i];
lang_index = i;
break;
}
}
if (lang_index === -1) {
document.getElementById("select-lang").style.display = 'none';
} else {
document.getElementById("select-lang").value = paths[lang_index];
}

const back = document.getElementById('back');
Expand All @@ -128,18 +144,6 @@ <h2>{{ site.description | default: site.github.project_tagline }}</h2>
back.innerText = 'Home';
}

const returnToBackPage = () => {
if (lang_index !== -1) {
if (lang_index + 2 === paths.length) {
window.location.href = paths.slice(0, lang_index).join('/') + '/';
} else {
window.location.href = paths.slice(0, lang_index + 1).join('/') + '/';
}
} else {
window.location.href = paths.slice(0, 4).join('/') + '/'
}
};

const redirectToLanguage = () => {
if (lang_index !== -1) {
paths[lang_index] = document.getElementById("select-lang").value;
Expand Down

0 comments on commit f12d519

Please sign in to comment.