I'm creating a multilingual Website with HUGO and I wanted to implement a language switcher via HUGO shortcodes. I've run into two problems, each with different code input. But it is all about the language switcher.
Problem 1: When i use this part of code. I'm getting this error:
execute of template failed at <.Page.Permalink>: can’t evaluate field Page in type *langs.Language
<ul>
{{ range .Site.Languages }}
<li>
<a href="{{ .Page.Permalink | relLangURL .Lang }}">{{ .LanguageName }}</a>
</li>
{{ end }}
</ul>
Problem 2: When I use this part of code. I'm getting a problem with switching back to the previous language. The link goes from example.com/en
to example.com/en/de
. And obviously this won't work.
<ul>
{{ range .Site.Languages }}
<li>
<a href="{{ .Lang | relLangURL }}">{{ .LanguageName }}</a>
</li>
{{ end }}
</ul>
My hugo.toml
is setup like this:
defaultContentLanguage = "de"
defaultContentLanguageInSubdir = true
[languages]
[languages.de]
title = "New Page"
languageName = "Deutsch"
languageCode = "de"
weight = 1
contentDir = "content/de"
[languages.de.menu]
[[languages.de.menu.main]]
identifier = "home"
name = "Home"
url = "/"
weight = 1
[[languages.de.menu.main]]
identifier = "about"
name = "Über mich"
url = "/about/"
weight = 2
[languages.en]
title = "New Page"
languageName = "English"
languageCode = "en"
weight = 2
contentDir = "content/en"
[languages.en.menu]
[[languages.en.menu.main]]
identifier = "home"
name = "Home"
url = "/"
weight = 1
[[languages.en.menu.main]]
identifier = "about"
name = "About Me"
url = "/about/"
weight = 2
What am I missing out? Did I use something deprecated (Hugo version v0.127.0)?
Classic context problem: The field.Page
does not exist in {{ range .Site.Languages }}
. The correct way to refer to it is by using $.Page
, where the dollar sign refers to the previous context.
This will be solved when you solve problem 1.
Here is the working code:
<ul>
{{ range .Site.Languages }}
<li>
<a href="{{ $.Page.Permalink | relLangURL .Lang }}">{{ .LanguageName }}</a>
</li>
{{ end }}
</ul>