Skip to content

Commit

Permalink
feat: redirect to the preferred language site on homepage
Browse files Browse the repository at this point in the history
  • Loading branch information
razonyang committed Apr 22, 2023
1 parent 2622b55 commit 1b80e5f
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 1 deletion.
23 changes: 23 additions & 0 deletions assets/js/preferred-lang/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { default as params } from '@params';

(() => {
const lang = navigator.language || navigator.userLanguage

// match the exact language code.
if (lang in params.homes) {
window.location.href = params.homes[lang]
return
}

// match the main language code.
const codes = lang.split('-')
for (let lang in params.homes) {
if (lang.indexOf(codes[0]) === 0) {
window.location.href = params.homes[lang]
return
}
}

// fallback to the default language.
window.location.href = params.fallback
})()
16 changes: 15 additions & 1 deletion layouts/alias.html
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,24 @@
<head>
{{- partial "assets/init/js" .Page -}}
{{- partialCached "assets/main/css" .Page }}
{{- $isHome := eq .Permalink (site.Sites.First.Home.Permalink) }}
{{- if $isHome }}
{{- $homes := newScratch }}
{{- range site.Sites }}
{{- $homes.Set .Home.Lang .Home.Permalink }}
{{- end }}
{{- $opts := dict
"minify" hugo.IsProduction
"targetPath" "js/preferred-lang.js"
"params" (dict "homes" $homes.Values "fallback" .Permalink)
}}
{{- $js := resources.Get "js/preferred-lang/index.ts" | js.Build $opts }}
<script src="{{ $js.RelPermalink }}"></script>
{{- end }}
<title>{{ .Permalink }}</title>
<link rel="canonical" href="{{ .Permalink }}"/>
<meta name="robots" content="noindex">
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<meta http-equiv="refresh" content="0; url={{ .Permalink }}"/>
<meta http-equiv="refresh" content="{{ cond $isHome `5` `0` }}; url={{ .Permalink }}"/>
</head>
</html>

0 comments on commit 1b80e5f

Please sign in to comment.