hugo-theme-stack/layouts/partials/head/autoLang.html
Alex Hua 5981551998 feat: auto-switch site lang when homepage visited
1. auto-switch site lang according to setting from sidebar
   or browser lang settings, when home page is visited.
2. save sidebar lang setting to local storage.
2023-04-08 19:41:03 +08:00

32 lines
987 B
HTML

{{ if .Site.IsMultiLingual }}
<script>
(function () {
const BASE_URL = '{{ .Site.BaseURL }}';
const DEFAULT_LANG = '{{ .Site.Language.Lang }}';
if (!window.location.href.endsWith(BASE_URL)) return;
let userLangList = [...navigator.languages];
if (localStorage.userLang)
userLangList.unshift(localStorage.userLang);
else
localStorage.userLang = userLangList[0].toLowerCase();
let supportLangs = new Set();
{{ range .Site.Languages }}
supportLangs.add('{{ .Lang }}');
{{ end }}
for (let userLang of userLangList) {
userLang = userLang.toLowerCase();
if (DEFAULT_LANG == userLang) {
return;
}
if (supportLangs.has(userLang)) {
window.location.href = window.location.href + userLang;
return;
}
}
})()
</script>
{{ end }}