Hi everyone!
My website is maintained in two languages (Serbian and English). I have a button in the header that switches the languages, with the following code
<li class="nav-item">
{{ range $.Site.Home.AllTranslations }}
{{ if not (eq .Language $.Site.Language) }}
<a class="nav-link" href="{{ .Permalink }}">{{ .Language.LanguageName }}</a>
{{ end }}
{{ end }}
</li>
My problem is the following:
- I am located at someurl/blog/post
- I click on the language change button
- The language changes, but I get redirected to someurl/en
And hereβs my desired scenario:
- I am located at someurl/blog/post
- I click on the language change button
- The language changes, and I get redirected to someurl/en/blog/post
Iβve tried multiple things, including {{ trim .Page.RelPermalink "/"}}
, but nothing seems to work.
Thanks in advance!
With this content structure:
content/
βββ en/
β βββ posts/
β β βββ _index.md
β β βββ post-1.md
β βββ _index.md
βββ sr/
βββ posts/
β βββ _index.md
β βββ post-1.md
βββ _index.md
And this site config:
defaultContentLanguage = 'sr'
defaultContentLanguageInSubdir = true
[languages.sr]
contentDir = 'content/sr'
languageCode = 'sr-RS'
languageName = 'Serbian'
weight = 1
[languages.en]
contentDir = 'content/en'
languageCode = 'en-US'
languageName = 'English'
weight = 2
Your language switcher should look something like:
{{ with .Translations }}
<nav class="language-switcher">
{{ range . }}
{{ if eq .Language.Lang $.Language.Lang }}
<a class="active" aria-current="page" href="{{ .RelPermalink }}">{{ .Language.LanguageName }}</a>
{{ else }}
<a href="{{ .RelPermalink }}">{{ .Language.LanguageName }}</a>
{{ end }}
{{ end }}
</nav>
{{ end }}
The conditional block is there in case you want to show all languages in the switcher by ranging over .Page.AllTranslations
instead of .Page.Tranlsations
.
Hm, itβs not working for me, although my current content structure is
content/
βββ post1.md
βββ post1.en.md
βββ _index.md
βββ _index.en.md
Are you suggesting moving to the one youβve described?
This example uses your content structure.
git clone --single-branch -b hugo-forum-topic-44031 https://github.com/jmooring/hugo-testing hugo-forum-topic-44031
cd hugo-forum-topic-44031
hugo server
Thanks, this is really useful! Iβll look into it and hopefully find the solution
1 Like