关于 React 的 i18Next 的信息很多,但对于需要仅使用标准 i18Next.js 进行翻译的网站来说却很少。
除了一件非常重要的事情之外,我一切都正常。我无法翻译
<input>
占位符和自定义属性。
我见过很多例子说你应该写:
<input type="text" data-i18n="[placeholder]MYKEY">
它应该输出:
<input type="text" placeholder="My Placeholder">
但事实并非如此。
在我的html中我可以写:
<p data-i18n="MYKEY"></p>
它翻译得很完美,所以我不确定我做错了什么。
这是我的初始化脚本:
<script src="/i18next/i18next.js"></script>
<script src="/i18next/i18nextHttpBackend.js"></script>
<script src="/i18next/i18nextBrowserLanguageDetector.js"></script>
<script>
i18next
.use(i18nextHttpBackend)
.use(i18nextBrowserLanguageDetector)
.init(
{
fallbackLng: 'en',
backend: {
loadPath: 'https://www.example.com/localization/{{lng}}_json',
}
}
)
.then(() => {
document.body.querySelectorAll('[data-i18n]').forEach(element => {
element.innerHTML = i18next.t(element.getAttribute('data-i18n'));
});
});
</script>
我使用 json 文件来编写这样的翻译:
{
"contact": {
"CONTACT_FORM_NAME_LABEL": "NAME",
"CONTACT_FORM_NAME_PLACEHOLDER": "Enter your name",
}
}
所以我的输入字段的实际 html 是:
<input type="text" data-i18n="[placeholder]contact.CONTACT_FORM_NAME_PLACEHOLDER">
我使用的是最新的 i18Next.js 版本 23.4.4。
答案是我需要为 i18next 加载 jquery 库并调整我的初始化脚本,如下所示:
<script>
i18next
.use(i18nextHttpBackend)
.use(i18nextBrowserLanguageDetector)
.init(
{
fallbackLng: 'en',
backend: {
loadPath: 'https://www.example.com/localization/{{lng}}_json',
}
}, (err, t) => {
if (err) return console.error(err);
jqueryI18next.init(i18next, $, { useOptionsAttr: true });
$('body').localize();
}
);
</script>
现在使用 data-i18n="KEY" 的所有内容都可以完美地包含字符串属性。
记住在所有 i18next javscript 之前加载 jquery。