I\'m using i18next to power i18n for my weblog. It works great on text-only content, but when I try to translate content that includes HTML markup, it is displaying the raw
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
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.
You can turn off the escaping during initialization globally:
i18n.init({
// ...
interpolation: {
escapeValue: false,
}
});
i18n.t('key',{dateStr: date, interpolation: {escapeValue: false}})
work for me if date='15/10/2020', slashes kept as well
You need to turn off escaping:
i18n.t("key", { 'interpolation': {'escapeValue': false} })
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 <tag> 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.