React 中 i18next 翻译文件中的 HTML 标签

新手上路,请多包涵

我在一个项目中使用 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, &lt;strong&gt;User!&lt;/strong&gt

谢谢

原文由 Petr Gazarov 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.4k
1 个回答

不要将 HTML 标签放在翻译中。无论如何这是个坏主意。 关注点分离的 人会对此大发牢骚。

使用 <Trans> 组件 if react-i18next https://react.i18next.com/latest/trans-component

这样做:

 // 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 的人在他们的文档中没有这个,但是您可以使用基本语言作为 (在本例中为英语)。它可以节省您的时间,而不是像他们在文档中显示的那样进行双重翻译,我引用:

 // 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 团队!你们真棒,伙计们!

在这里 - 去疯了

原文由 viktor_vangel 发布,翻译遵循 CC BY-SA 4.0 许可协议

推荐问题