mirror of
https://github.com/CaiJimmy/hugo-theme-stack.git
synced 2025-06-18 03:53:31 +08:00
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.
This commit is contained in:
parent
9d22841a4e
commit
5981551998
@ -6,6 +6,7 @@
|
||||
</head>
|
||||
<body class="{{ block `body-class` . }}{{ end }}">
|
||||
{{- partial "head/colorScheme" . -}}
|
||||
{{- partial "head/autoLang" . -}}
|
||||
|
||||
{{/* The container is wider when there's any activated widget */}}
|
||||
{{- $hasWidget := false -}}
|
||||
|
31
layouts/partials/head/autoLang.html
Normal file
31
layouts/partials/head/autoLang.html
Normal file
@ -0,0 +1,31 @@
|
||||
{{ 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 }}
|
@ -80,9 +80,9 @@
|
||||
{{ with .Site.Home.AllTranslations }}
|
||||
<li id="i18n-switch">
|
||||
{{ partial "helper/icon" "language" }}
|
||||
<select name="language" onchange="window.location.href = this.selectedOptions[0].value">
|
||||
<select name="language" onchange="localStorage.userLang = this.selectedOptions[0].dataset.lang; window.location.href = this.selectedOptions[0].value">
|
||||
{{ range . }}
|
||||
<option value="{{ .Permalink }}" {{ if eq .Language.Lang $currentLanguageCode }}selected{{ end }}>{{ .Language.LanguageName }}</option>
|
||||
<option data-lang="{{ .Language.Lang }}" value="{{ .Permalink }}" {{ if eq .Language.Lang $currentLanguageCode }}selected{{ end }}>{{ .Language.LanguageName }}</option>
|
||||
{{ end }}
|
||||
</select>
|
||||
</li>
|
||||
|
Loading…
Reference in New Issue
Block a user