前面的三篇文章中,我们已经拥有了本地化所需的一些基本功能,但如果在无法精准匹配当前语言的情况下,如何寻找上一层级的语言包,则是获取语言文本的最重要的一环。为此,我们需要实现以下步骤。
- 尝试获取预期语言的对应文本,有的话则返回之,没有的话继续。
- 检查语言代号标识中是否包含短横线(-),有的话则继续,没有的话则返回从默认语言的语言包中检索的结果。
- 找到最后一个短横线。
- 删除该短横线后面的内容。
- 返回第一步,重新来一遍。
代码如下。
/**
* Gets the string in local or specific language.
* @param key The template key.
* @param useKeyInsteadOfUndefined true if use key as result instead of undefined; otherwise, false.
* @param lang The opitonal ISO 639 code string for a sepecific one.
*/
Local.prototype.getString = function (key, useKeyInsteadOfUndefined, lang) {
var langCode = !lang ? Local.lang() : lang;
if (!langCode || langCode == "") langCode = this.defaultLang;
var str = this.specificString(langCode, key);
if (!!str || typeof str !== "undefined") return str;
while (langCode.lastIndexOf("-") > 1) {
langCode = langCode.substring(0, langCode.lastIndexOf("-"));
str = this.specificString(langCode, key);
if (!!str || typeof str !== "undefined") return str;
}
return useKeyInsteadOfUndefined ? key : undefined;
}
现在,我们可以获取最匹配的文本了。接着上一篇文章的测试代码,我们再来测试一下。
// 继续上一段测试代码。
// var local = new Local();
// ...
// 假设当前语言环境是 zh-Hans。
console.debug(local.getString("goodbye")); // "再见!"
console.debug(local.getString("hello")); // Undefined
console.debug(local.getString("hello", true)); // "hello"
console.debug(local.getString("bye", false, "en")); // "Bye!"
是不是很棒?等等,还有更棒的!有的时候,你可能需要将一批需要用到的文本复制到一个对象上,例如,当使用诸如 AngularJs 时,你需要将这些信息存储到 $scope 中的某个属性里,以方便在视图中使用。因此,我们还需要提供一些类似方法,来支持这一类的功能,可以将指定的一组文本映射到一个对象上并返回。
/**
* Copies a set of strings to an object as properties.
* @param keys The template keys.
*/
Local.prototype.copyStrings(keys) {
var obj = {};
keys.forEach(function (key, i, arr) {
obj[key] = this.localString(key);
});
return obj;
}
然后我们继续来个简单的测试。
// 继续上一段测试代码。
// var local = new Local();
// ...
// 假设当前语言环境是 zh-Hans。
var strings = local.copyStrings(["bye", "hello"]);
console.debug(strings.goodbye); // "再见"
console.debug(strings.greetings); // "嗨!"
console.debug(strings.hello); // Undefined
现在,你已经拥有了一套基本的 Web 前端本地化解决方案了。
【完】
文章类型及复杂度:Web 前端开发进阶。
节选翻译自 MSDN 博文 Localization in web page,内容有所调整。
http://blogs.msdn.com/b/kingcean/archive/2016/03/30/web-localization.aspx