Changing languages and remaining on the same page

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