HUGO

Is it possible to access all the translations programatically?

I’ve asked this question on stack overflow, but to summarize: Can I access all the i18n keys and translations in the i18n folder? For instance, using the Data syntax, how would I do something like the following:

{{ range $.Site.i18n.en }}
  <p>{{ .id }} - {{ .translation }}</p>
{{ end }}

See Get i18n string from arbitrary language (not current page's language) and https://github.com/gohugoio/hugo/issues/7844.

Thanks for pointing those out. It looks like those might point to ways to get to an individual page’s translation, but I’m trying to get all the translations for a given i18n file. For example, if I have a file at i18n/es.yaml that looks like the following:

- id: browsePlays
  translation: Explorar Jugadas
- id: categories
  translation: Categorias
- id: search
  translation: Buscar

Is there something I could range over to get each of the defined ids and translations, e.g.:

{{ range $.Site.i18n.es }}
  <li>{{ .id }} - {{ .translation }}</li>
{{ end }}

to output

  • browsePlays - Explorar Jugadas
  • categories - Categories
  • search - Buscar

Does that make sense?

It’s not possible. You could copy the file into the data folder and use the Data Templates feature of Hugo:

In my head you have 2 options:

  1. Mount the i18n folder somewhere inside /data (e.g. So /data/i18n) and then access the languages in this map.
  2. Do the same, but in /assets and use resources.Match etc. and transform.Unmarshal to turn it into a data structure.

Currently option 1 and 2 is a little bit “matter of taste”, but I will soon merge a patch I’ve been working on that will make 2) the very best option for data you only use in a small part of your site, esp. for “big data”.

4 Likes

@bep Can I still use the i18n function with either of those? For what it’s worth, I tried the following in my config.toml hoping that would work:

[module]
[[module.mounts]]
source="data"
target="data"
[[module.mounts]]
source="i18n"
target="data/i18n"

The i18n function still worked and I could still use things like .Site.Language.Lang, but {{ $.Site.Data.i18n.en | jsonify }} still came back as nil.

I’ll have to look into the resources.Match and transform.Unmarshal and I’ll report back on my findings.

For what it’s worth, the reason why I’m attempting this is that I have a Hugo site for an international audience where 95% of it is handled by Hugo. There’s a small javascript (React) app that is also embedded on a page. I’d like to have all the site translations in one location, and then have the React app grab those translations for use in its own i18n functions. Worst case, I can do something separate or maybe go the opposite route of storing the {lang}.yml files more closely affiliated with the React app and mount them into the /i18n directory.