根据 HTML 标签设置 i18next 语言
Set i18next language based on HTML tag
好的,所以我正在试验 ReactJS 和 i18next。
我想在初始页面加载时设置我的翻译语言基于
一些 html 标签。
例如,如果我在页面加载时有 <html lang="de">
,我希望有
在进行任何翻译之前,lng
设置为 de
。
这是我的 i18n.js
文件的内容:
import i18n from "i18next";
import { initReactI18next } from "react-i18next";
// the translations
// (tip move them in a JSON file and import them)
const resources = {
en: {
translation: {
"Welcome to React": "Translation in English"
}
},
de: {
translation: {
"Welcome to React": "Translation in German"
}
}
};
i18n
.use(initReactI18next) // passes i18n down to react-i18next
.init({
resources,
lng: "en",
keySeparator: false, // we do not use keys in form messages.welcome
interpolation: {
escapeValue: false // react already safes from xss
}
});
export default i18n;
来自here
const htmlLang = document.documentElement.lang; // for <html lang=".."> not xml-lang:".."
现在你可以把这个常量放在你的 i18n 声明中
i18n
.use(initReactI18next) // passes i18n down to react-i18next
.init({
resources,
lng: htmlLang,
keySeparator: false, // we do not use keys in form messages.welcome
interpolation: {
escapeValue: false // react already safes from xss
},
fallbackLng: ['en', //'fr', ...]
});
我还添加了后备语言
好的,所以我正在试验 ReactJS 和 i18next。
我想在初始页面加载时设置我的翻译语言基于 一些 html 标签。
例如,如果我在页面加载时有 <html lang="de">
,我希望有
在进行任何翻译之前,lng
设置为 de
。
这是我的 i18n.js
文件的内容:
import i18n from "i18next";
import { initReactI18next } from "react-i18next";
// the translations
// (tip move them in a JSON file and import them)
const resources = {
en: {
translation: {
"Welcome to React": "Translation in English"
}
},
de: {
translation: {
"Welcome to React": "Translation in German"
}
}
};
i18n
.use(initReactI18next) // passes i18n down to react-i18next
.init({
resources,
lng: "en",
keySeparator: false, // we do not use keys in form messages.welcome
interpolation: {
escapeValue: false // react already safes from xss
}
});
export default i18n;
来自here
const htmlLang = document.documentElement.lang; // for <html lang=".."> not xml-lang:".."
现在你可以把这个常量放在你的 i18n 声明中
i18n
.use(initReactI18next) // passes i18n down to react-i18next
.init({
resources,
lng: htmlLang,
keySeparator: false, // we do not use keys in form messages.welcome
interpolation: {
escapeValue: false // react already safes from xss
},
fallbackLng: ['en', //'fr', ...]
});
我还添加了后备语言