i18n Attaching variable to translation string

Viewed 14113

I am currently using i18n to translate strings and I'm looking for a way to attach a variable onto the path.

This variable could be about 8 different values and each need a different translation. My locale files already include the translations but I don't know how to add my variable onto the translation path. I don't think variable interpolation helps me here.

content.state //variable
t ('.state') //locale path

I'm looking for a way to add the content.state variable to the end of the locale path so that it translates depending on what content.state is. Currently my only solution is a large if/else covering all the states.

Solved: I was trying to find a way to add a variable to the locale path inside handlebars and ended up using the concat helper.

{{ t (concat "state." content.state)}}
2 Answers

I was looking for this too. My problem was to be able to add a variable into the link to the translation. I managed it perfectly using the context.

Let's say you want to show "English" and "French" when "en" and "fr" are returned from your back-end.

In your translation files (en.json and fr.json) add the context:

{
  ...
  "language_en":"English",
  "language_fr":"French",
  ...
}

And in your front-end, saying your variable name is objectLanguage, use the context with:

t('language', { context: objectLanguage })

i18next will look to the specific context and render corretly "English" or "French"!

Documentation can be find here.

EDIT: even easier, you can use the quote marks, if you code:

t(`language.${objectLanguage}.label`)

To point to the links:

{
  ...
  "language.en.label":"English",
  "language.fr.label":"French",
  ...
}

It will works fine too.

Hop this can help someone.

Related