HTML tags in i18next translation

徘徊边缘 提交于 2019-11-28 21:06:29

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} })

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.

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 present user input here, be sure to sanitise or escape the user's string, so the user cannot inject raw < or > into the page.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!