最佳实践 javascript 和多语言
使用 DOM 和 javascript 操作的多语言网站的最佳实践是什么?我使用 javascript 构建网站的一些动态部分.我的第一个想法是使用带有文本字符串和语言代码的数组作为索引.这是个好主意吗?
what is the best practice for multilanguage website using DOM Manipulating with javascript? I build some dynamic parts of the website using javascript. My first thought was using an array with the text strings and the language code as index. Is this a good idea?
推荐答案
我以前建过多语种网站(不是很大,所以可能规模不大),我保留了一系列语言"文件:
When I've built multi-lingual sites before (not very large ones, so this might not scale too well), I keep a series of "language" files:
- lang.en.js
- lang.it.js
- lang.fr.js
每个文件都声明了一个对象,该对象基本上只是从关键字到语言短语的映射:
Each of the files declares an object which is basically just a map from key word to language phrase:
// lang.en.js
lang = {
greeting : "Hello"
};
// lang.fr.js
lang = {
greeting : "Bonjour"
};
动态加载其中一个文件,然后您需要做的就是从地图中引用密钥:
Dynamically load one of those files and then all you need to do is reference the key from your map:
document.onload = function() {
alert(lang.greeting);
};
当然,还有很多其他方法可以做到这一点,还有很多方法可以做到这一点,但更好:将它们全部封装到一个函数中,以便可以优雅地处理字典"中丢失的短语,甚至可以做整个过程使用 OOP,并让它管理文件的动态,它甚至可以为您绘制语言选择器等.
There are, of course, many other ways to do this, and many ways to do this style but better: encapsulating it all into a function so that a missing phrase from your "dictionary" can be handled gracefully, or even do the whole thing using OOP, and let it manage the dynamic including of the files, it could perhaps even draw language selectors for you, etc.
var l = new Language('en');
l.get('greeting');
相关文章