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 markup when I translate the text.
As an example, here is a snippet of the markup from a post that is not working as expected:
<div class="i18n" data-i18n="content.body">
In Medellín they have many different types of <i>jugos naturales</i> (fruit juice) ... <br />
<br />
...
</div>
The translation code looks like this:
var resources = {
"en": ...,
"es": {
"translation": {
"content": {
"body": "En Medellín hay varios tipos diferentes de <i>jugos naturales</i> ... <br /><br /> ... "
}
}
}
}
i18n.init({"resStore": resources}, function( t ) {
$('.i18n').i18n();
});
When the translation is rendered, HTML tags are escaped and output as text:
En Medellín hay varios tipos diferentes de <i>jugos naturales</i>...<br /><br />
How do I get i18next to change the HTML of translated elements?
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 <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.
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.
来源:https://stackoverflow.com/questions/16038458/html-tags-in-i18next-translation