Best practice javascript and multilanguage(最佳实践 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 和多语言的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:最佳实践 javascript 和多语言
- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- 失败的 Canvas 360 jquery 插件 2022-01-01
- Flexslider 箭头未正确显示 2022-01-01
- Fetch API 如何获取响应体? 2022-01-01
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- 400或500级别的HTTP响应 2022-01-01
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- addEventListener 在 IE 11 中不起作用 2022-01-01
