使用 i18next 对静态 HTML 进行本地化(加载本地 json 翻译文件)
Localization of static HTML with i18next (loading local json translation files)
我的项目只有 HTML。我不会使用节点或反应版本。
我试过默认示例,效果很好
<div id="output" />
<script src="https://unpkg.com/i18next/dist/umd/i18next.min.js"></script>
<script>
i18next.init({
lng: 'en',
debug: true,
resources: {
en: {
translation: {
"key": "Hello World"
}
},
de: {
translation: {
"key": "hello welt"
}
}
}
}, function(err, t) {
// init set content
updateContent();
});
function updateContent() {
document.getElementById('output').innerHTML = i18next.t('key');
}
function changeLng(lng) {
i18next.changeLanguage(lng);
}
i18next.on('languageChanged', () => {
updateContent();
});
</script>
但我不知道如何加载本地 json 文件而不是将所有翻译放在 js 中。我是否必须安装额外的插件才能加载 json 个翻译文件?
这是针对 HTML 中每个字符串的正确方法吗?
function updateContent() {
document.getElementById("homeTitle").innerHTML = i18next.t("home.title");
document.getElementById("homeSubtitle").innerHTML = i18next.t("home.subtitle");
}
有没有办法将属性添加到 HTML 字符串,例如
<h1 data-i18n="home.title"></h1>
要获取翻译?
您可以使用 fetch 加载它们,运行 一堆承诺。
我用 vanilla JS 为你写了一个 sandbox code example。
PS: 不知道为什么,打开代码沙盒的时候代码执行不好,需要刷新本地预览才能生效(或者你可以尝试从 here) 打开预览,但我在我的开发环境中通过 Live Server 对其进行了测试,它工作正常。
我的项目只有 HTML。我不会使用节点或反应版本。
我试过默认示例,效果很好
<div id="output" />
<script src="https://unpkg.com/i18next/dist/umd/i18next.min.js"></script>
<script>
i18next.init({
lng: 'en',
debug: true,
resources: {
en: {
translation: {
"key": "Hello World"
}
},
de: {
translation: {
"key": "hello welt"
}
}
}
}, function(err, t) {
// init set content
updateContent();
});
function updateContent() {
document.getElementById('output').innerHTML = i18next.t('key');
}
function changeLng(lng) {
i18next.changeLanguage(lng);
}
i18next.on('languageChanged', () => {
updateContent();
});
</script>
但我不知道如何加载本地 json 文件而不是将所有翻译放在 js 中。我是否必须安装额外的插件才能加载 json 个翻译文件?
这是针对 HTML 中每个字符串的正确方法吗?
function updateContent() {
document.getElementById("homeTitle").innerHTML = i18next.t("home.title");
document.getElementById("homeSubtitle").innerHTML = i18next.t("home.subtitle");
}
有没有办法将属性添加到 HTML 字符串,例如
<h1 data-i18n="home.title"></h1>
要获取翻译?
您可以使用 fetch 加载它们,运行 一堆承诺。 我用 vanilla JS 为你写了一个 sandbox code example。
PS: 不知道为什么,打开代码沙盒的时候代码执行不好,需要刷新本地预览才能生效(或者你可以尝试从 here) 打开预览,但我在我的开发环境中通过 Live Server 对其进行了测试,它工作正常。