Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML tags in i18next translation

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


You need to turn off escaping:

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


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.


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

work for me if date='15/10/2020', slashes kept as well


From the documentation:

Hint 3: Escaping:

// given resources
{           
  'en-US': { 
    translation: { 
      key1: Not escaped __nameHTML__,
      key2: Escaped __name__ 
    } 
  }
};

i18n.t("key2", { name: '', escapeInterpolation: true }); // -> Escaped &lt;tag&gt;
i18n.t("key1", { name: '', escapeInterpolation: false }); // -> Not escaped <tag>

Adding suffix 'HTML__' to your value will prevent the escaping even if option is set so.

You could turn on escaping on init i18n.init({escapeInterpolation: true}); or by passing in option to t function like in the sample.


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


You can turn off the escaping during initialization globally:

i18n.init({
  // ...
  interpolation: {
    escapeValue: false,
  }
});