我的网络应用没有很多字母。单词表示按钮,标题等。因此,我想知道是否可以使用Globalize.js库切换语言。例如:如果我更改设置,我希望我的“注册”按钮切换为法语。
答案 0 :(得分:-1)
首先,您需要为其他语言编写一个带有json内容的其他消息文件,例如:
{
"fr": {
"register": "s'inscrire"
}
}
然后,您可以使用javascript从服务器获取其数据,并将其传递给全球化:
const fetchHeaders = new Headers({"accept": "application/json", 'X-Requested-With': 'XMLHttpRequest'});
fetch("messages/" + locale + ".json", { headers: fetchHeaders }).then(response => {
return response.json();
})
.then(
json => {
Globalize.loadMessages(json);
Globalize.locale(locale);
yourRender();
});
此处locale
是保存新语言环境的变量。如果为'fr',则上面的代码希望文件位于messages/fr.json
上的服务器上。
yourRender
是一项功能,您可以自己编程以将消息更新为按钮等:
function yourRender() {
document.getElementById( "button-1" ).value = Globalize.formatMessage( "register" );
// etc
}
如果您还需要使用Globalize格式化并解析日期和数字,则情况将变得复杂。为此,您需要获取服务器文件的内容并将其加载到Globalize中。这将异步发生,因此您需要跟踪已加载的数量,并且仅在全部加载后才进行跟踪,将语言环境放在Globalize上,创建新的格式化函数并调用yourRender()。有关完整示例(使用webpack),请参见我的switch language example on Github。