How to merge frontmatter of multilanguage MD files

I have page.md and page.fr.md. I would like NOT to repeat some frontmatter params, as en is the default and some are the same. In other words, I would like to merge frontmatter of the translation with the default language.

How to do so?

I am in the same situation and could not find any way to handle it. Are you aware of any related Github Issues or proposals ?

First you need to grab your original page from the template. I guess the easiets way is this:

// If site language is not en (hugo is processing a french page)
{{ if (ne site.Language.Lang "en")
   // if the page has translations
    {{ with .Translations }}
      // range on those translations
      {{ range . }}
        // if one of them is the english translation then store it in your variable.
        {{ if eq .Language.Lang "en" }}
          {{ $translation = . }}
        {{ end }}
      {{ end }}
    {{ end }}
  {{ end }}

With the code above you were able to retrieve the page object of page.md from the template processing page.fr.md. Then you can use merge to merge the two params object.

{{ $params := merge $translation.Params $.Params }}

Of course your should remove those non-Go Template comments and set defaults variable to avoid your build breaking if no translation is found etc…

2 Likes

ah, got the idea, thanks regis
I am using this adapted version now:

{{ $params := .Params }}
{{ if ne .Language .Sites.First.Language }}
{{ $params = merge (index .Translations 0).Params .Params }}
{{ else }}
{{ $params = .Params }}
{{ end }}
1 Like

That’s good! I admit my example was a bit verbose but it was also futureproof.

  1. Be aware your build will break if any of your non english entry is momentarily missing a translation. You should check for any translations before calling that .Params on the first one.
  2. Also you might have to revisit that code if you introduce a third language.

My own 2 cents :wink: