i18n.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /*
  2. * Utilities: A classic collection of JavaScript utilities
  3. * Copyright 2112 Matthew Eernisse ([email protected])
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. *
  17. */
  18. var core = require('./core')
  19. , i18n;
  20. var DEFAULT_LOCALE = 'en-us';
  21. i18n = new (function () {
  22. var _defaultLocale = DEFAULT_LOCALE
  23. , _strings = {};
  24. this.getText = function (key, opts, locale) {
  25. var currentLocale = locale || _defaultLocale
  26. , currentLocaleStrings = _strings[currentLocale] || {}
  27. , defaultLocaleStrings = _strings[_defaultLocale] || {}
  28. , str = currentLocaleStrings[key]
  29. || defaultLocaleStrings[key] || "[[" + key + "]]";
  30. for (var p in opts) {
  31. str = str.replace(new RegExp('\\{' + p + '\\}', 'g'), opts[p]);
  32. }
  33. return str;
  34. };
  35. this.getDefaultLocale = function () {
  36. return _defaultLocale;
  37. };
  38. this.setDefaultLocale = function (locale) {
  39. _defaultLocale = locale;
  40. };
  41. this.loadLocale = function (locale, strings) {
  42. _strings[locale] = _strings[locale] || {};
  43. core.mixin(_strings[locale], strings);
  44. };
  45. })();
  46. i18n.I18n = function (locale) {
  47. var _locale = locale || i18n.getDefaultLocale();
  48. this.getLocale = function (locale) {
  49. return _locale;
  50. };
  51. this.setLocale = function (locale) {
  52. _locale = locale;
  53. };
  54. this.getText = function (key, opts, locale) {
  55. return i18n.getText(key,
  56. opts || {}, locale || _locale);
  57. };
  58. this.t = this.getText;
  59. };
  60. module.exports = i18n;