我有以下问题:我使用i18next react,也使用i18next后端加载我的翻译文件。我有一个语言切换器,我不仅想用它来改变语言,还想用它来改变URL。但是,在更改语言之前,我需要访问新语言的命名空间“路由”。我该怎么做?
这是我的国际化配置:
i18n
.use(initReactI18next)
.use(detector)
.use(HttpApi)
.init({
defaultNS: 'routes',
fallbackLng: ['de'],
supportedLngs: ['de', 'en'],
detection: {
order: ['path'],
lookupFromPathIndex: 0,
},
backend: {
loadPath: '/locales/{{lng}}/{{ns}}.json',
},
keySeparator: false,
interpolation: {
format,
},
});
export default i18n;
我的语言选择器使用这个函数:
changeLanguage = (ln) => {
const routes = i18n.getResourceBundle(i18n.language, 'routes');
const currentPathname = window.location.pathname.replace(/\/+$/, '');
let currentRouteKey = Object.keys(routes).find((key) => routes[key] === currentPathname);
if (ln === 'en' && currentPathname === '') {
currentRouteKey = '/en';
}
window.location.replace(this.props.t('routes:' + currentRouteKey, { lng: ln }));
};
德语是我的后备语言,当我从应用程序的英文版本开始时,语言更改会起作用,但是当我从德语版本开始时,它不起作用。我想这是因为英文文件没有加载。如何触发此文件?
代替整页重新加载(使用location.replace
),您可以触发i18next.changeLangauge
来更改语言,在后台库将加载缺失的语言,然后您可以使用历史Api来更改URL。
// pseudo code
changeLanguage = (ln) => {
i18n.changeLanguage(lng, (err) => {
if (err) {
// handle language change error
}
const pathnameParts = window.location.pathname.split("/");
const currentLangPath = pathnameParts[1]; // skips the first slash
let newPathnameParts = pathnameParts;
if (i18n.options.supportedLngs.includes(currentLangPath)) {
newPathnameParts = newPathnameParts.slice(2); // removes the lang part
}
newPathnameParts = [lngSubPaths[lng]].concat(
newPathnameParts.filter(Boolean)
);
const newPathname = newPathnameParts.join("/");
if (newPathname !== window.location.pathname) {
window.history.pushState(null, "", newPathname);
}
});
};
工作代码和盒子示例
X2.2.0新增 sp_check_lang() 功能: 判断当前的语言包,并返回语言包名 参数: 无 返回: 类型string 包名,如:zh-cn 使用: $lang=sp_check_lang();
过去,我一直无法相信:一个新人在三个月里可以学好前端。后来,我信了。因为三个月后,我又是一个前端的新人,我又需要重新入门前端。 前端领域好似也有一个“摩尔定律”。戈登·摩尔提出来:积体电路上可容纳的电晶体(晶体管)数目,约每隔24个月便会增加一倍,后来经常被引用的“18个月”。而对于前端领域来说,每隔 3-6 个月,知识点将增加一倍。 过去一年(即 2016 年)的每三个月(或者半年)里,前端领域
问题内容: 我尝试使用输入获得当前选择的文本,但我总是得到一个空字符串: 结果成: 使用angularjs.org作为目标站点的完整可重复测试: 请注意,我实际上看到输入的文本是用COMMAND +“ a”选择的。 我究竟做错了什么? 使用量角器2.5.1,Firefox 41。 问题答案: 不适用于在元素中选择的文本,但不适用于在页面中对元素进行的选择。 您可以使用和这样的: 您可能应该为此创建
问题内容: 您可以使用鼠标选择网页的一部分。 我知道可以获取当前选择的文本,但是如何获取包含当前选择的开始或结束的DOM元素? 问题答案: 在IE中,使用document.selection.createRange()。parentElement(),在实际的浏览器中,使用window.getSelection()。getRangeAt(0).startContainer.parentNode。像
问题内容: 我正在使用React 和开发一个多语言应用程序。 我通过以下方式初始化i18next: 而且我实现了一个语言选择器,该选择器仅将中的值更改为用户选择的值。 这是正确的做法吗? 我问,因为即使这可行,但我仍然感觉自己在通过设置进行“欺骗”,并且我没有按原样使用语言检测。 问题答案: 根据文档,您不需要自己指定语言: 而根据这片源中,它的确使用了插件的检测能力: 这是正确的做法吗? 所以,