最佳实践javascript和多语言 [英] Best practice javascript and multilanguage

查看:104
本文介绍了最佳实践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');

这篇关于最佳实践javascript和多语言的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆