我在一个项目中使用 i18next,无法在翻译文件中包含 html 标签并正确呈现它们。
我的
.json
翻译文件的例子:
"en": {
"product": {
"header": "Welcome, <strong>User!</strong>"
}
}
这个问题有一个很好的答案,但与 JQuery 有关。我没有使用 JQuery,我的项目是 React,这是我的设置:
import i18next from 'i18next';
import en from 'locales/en';
i18next.
init({
lng: 'en',
fallbackLng: false,
resources: en,
debug: false,
interpolation: {
escapeValue: false
}
});
export default i18next.t.bind(i18next);
在组件中我有:
import t from 'i18n';
t('product.header')
我想要的HTML:
Welcome, <strong>User!</strong>
Html 我得到:
Welcome, <strong>User!</strong>
谢谢
不要将 HTML 标签放在翻译中。无论如何这是个坏主意。 关注点分离 伙计们会为此发牢骚。
如果
react-i18nexthttps://react.i18next.com/latest/trans-component使用
<Trans>
组件
这样做:
// Component.js
<Trans>Welcome, <strong>User!</strong>, here's your <strong>broom</strong></Trans>
以及对应的翻译文件:
// 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>",
}
这些数字 <1> 和 <3> 会让你觉得随机但等待它:
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
]
旁注(可以被认为是 hack,但可以节省大量时间): react.i18next.com 的人,他们的文档中没有这个,但是您可以使用基本语言作为key(英语在这种情况下)。它可以节省您的时间,而不是像他们在文档中显示的那样进行双重翻译,我引用:
// Component file
import React from 'react';
import { Trans } from 'react-i18next'
function MyComponent({ person, messages }) {
const { name } = person;
const count = messages.length;
return (
<Trans i18nKey="userMessagesUnread" count={count}>
Hello <strong title={t('nameTitle')}>{{name}}</strong>, you have {{count}} unread message. <Link to="/msgs">Go to messages</Link>.
</Trans>
);
}
// translation file
"userMessagesUnread": "Hello <1>{{name}}</1>, you have {{count}} unread message. <5>Go to message</5>.",
"userMessagesUnread_plural": "Hello <1>{{name}}</1>, you have {{count}} unread messages. <5>Go to messages</5>.",
无论如何“荣誉!”到 i18next 团队!你们真棒,伙计们!
这里 - 发疯!
自
[email protected]
以来,您可以在翻译字符串中使用标签,并将其替换为 components
组件中的 Trans
属性或 t
钩子中的 useTranslation
属性:
https://react.i18next.com/latest/trans-component#using-with-react-components
使用示例:
<Trans
i18nKey="myKey" // optional -> fallbacks to defaults if not provided
defaults="hello <italic>beautiful</italic> <bold>{{what}}</bold>" // optional defaultValue
values={{ what: 'world'}}
components={{ italic: <i />, bold: <strong /> }}
/>
不是 react-i18next 的问题——你只是不能将 html 添加到 react 元素中。 React 将保护您免受 xss 漏洞并转义内容:
更多细节和可能的解决方案:https://facebook.github.io/react/tips/dangerously-set-inner-html.html
但请注意,如果您将用户内容放在那里没有逃脱,您将打开您的网站以进行 xss 攻击。
阅读 react-i18next 自述文件更安全: https://github.com/i18next/react-i18next#interpolate-component
这让你分裂内容
所以“最佳”解决方案 - 至少我们所做的 - 是在翻译中使用降价并使用例如:https://github.com/acdlite/react-remarkable 将其转换为格式化内容。
首先你需要这样写你的json文件:
“恩”:{ “欢迎欢迎”, “用户”:“用户” }
然后编写你的HTML代码如下:
{t('欢迎')},{t('用户')}!