I have a Hugo site has two languages support: English and Chinese.
The localization is simple stuff, I use i18n to do some localization of strings, I use a translation table to localize section titles or some header texts etc. I don’t need separate urls like: example.com/en or example.com/cn.
Now everything is works, if I set defaultContentLanguage to “zh”, it shows the website with Chinese translation, it I set defaultContentLanguage to “en”, it shows the English translation, the only thing I don’t know how to do is to detect the browser language and show the translation accordingly, like, if I set the browser language to Chinese, it shows the Chinese translation, or fallback to the default English translation. Right now, no mater what language my browser is set, the website is the translation of I set to the defaultContentLanguage dynamically.
What I am asking and don’t know how to do is: is there a way to set defaultContentLanguage based on the browser language? I though it was simple, but I don’t know how to do it.
I assume that this can be solved with the help of js:
<script>
var userLang = navigator.language || navigator.userLanguage;
var url = window.location.href;
// if chinese and not /cn/ then redirect to /cn/
if (userLang.includes('zh') && !url.includes('/cn/')) {
window.location.href = url.replace(/\/$/, '') + '/cn/';
// else if not in /en/ then redirect to /en/
} else if (!url.includes('/en/')) {
window.location.href = url.replace(/\/$/, '') + '/en/';
}
</script>
But even this leaves questions. What if a person wants to read the English version while being on the Chinese version? In my opinion, it’s easier to make a standard version in your most popular language for users and in the interface, make a language change link like this:
{{ range $.Site.Home.AllTranslations }}
<a href="{{ .RelPermalink }}">{{ .Language.LanguageName }}</a>
{{ end }}
Thanks for the reply. I don’t think a language change link was needed for my blog, I just need translate the section or tags title based on user’s browser languages. I guess I have to separate the url for different languages using your script.