HTML tags in i18next translation

Solution 1:

In order to make this work, you have to prefix the data-i18n attribute of the elements you want to translate with [html]:

<div class="i18n" data-i18n="[html]content.body">

Source: i18next.jquery.js

Solution 2:

You need to turn off escaping:

i18n.t("key", { 'interpolation': {'escapeValue': false} })

Solution 3:

For anyone trying to do this in React (for example with react-i18-next), be aware that React also escapes the string! So we have to tell both i18n and React not to escape the string.

  • To tell i18n to skip escaping, we use {escapeValue: false} as others have shown.

  • To tell React to skip escaping, we use React's dangerouslySetInnerHTML attribute.

<div dangerouslySetInnerHTML={
    {__html: t('foo', {interpolation: {escapeValue: false}})}
} />

That attribute accepts an object with one property __html. React intentionally made it ugly, to discourage its use, because not escaping can be dangerous.

For security, raw user input should not be used inside this element. If you do need to use an untrusted string here, be sure to sanitise or escape it, so the user cannot inject raw < or > into the page.

Solution 4:

Don't put the HTML tags in the translation. It's a bad idea anyway. Separation of concerns guys will be all whiny about it.

Use the <Trans> component if react-i18next [https://react.i18next.com/latest/trans-component][1]

Do like so:

// Component.js

<Trans>Welcome, <strong>User!</strong>, here's your <strong>broom</strong></Trans>

And the corresponding translation file:

// your locales/starwars_en.js file

translations: {
  "Welcome, <1>User!</1>, here's your <3>broom</3>": "Welcome, <1>young padawan!</1>, here's your <3>light saber</3>",
}

These numbers <1> and <3> will strike you as random but wait for it:

Trans.children = [
  'Welcome, ',                        // index 0
  '<strong>User!</strong>'            // index 1
  ', please don't be ',               // index 2
  '<strong>weak</strong>',            // index 3
  ' unread messages. ',               // index 4
]

More info here: https://stackoverflow.com/a/62563302/537648