How to get a specific translation?

1) Collections

.Translations returns a collection of the current page’s translations, excluding the current page.

.AllTranslations returns a collection of the current page’s translations, including the current page.

2) .Language vs .Language.Lang

{{ printf "%T" .Language }} --> *langs.Language
{{ printf "%T" .Language.Lang }} --> string

In the where function you are comparing a value of type “*langs.Language” to a value of type “string”. That will always be false.

Instead of this:

{{ where .AllTranslations "Language" "de" }}

Do this:

{{ where .AllTranslations "Language.Lang" "de" }}

3) Get the page

The where function returns a collection (in this case with one item), not a page. So, this will not work.

{{ $p := where .AllTranslations "Language.Lang" "de" }}
{{ $p.Title }}

You need to range through the collection to get the page.

{{ $p := slice }}
{{ range where .AllTranslations "Language.Lang" "de" }}
  {{ $p = . }}
{{ end }}
<a href="{{ $p.RelPermalink }}">{{ $p.Title}} ({{ $p.Language.Lang }})</a>

Or use the index function to get the first (and only) item:

{{ $p := index (where .AllTranslations "Language.Lang" "de") 0 }}
<a href="{{ $p.RelPermalink }}">{{ $p.Title}} ({{ $p.Language.Lang }})</a>

4) Supression of duplicate warnings

See https://gohugo.io/functions/errorf/.

errorf or warnf will evaluate a format string, then output the result to the ERROR or WARNING log (and only once per error message to avoid flooding the log).

3 Likes