Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

add translation support

  • Loading branch information...
commit 4e12b643528a7d6aa713fd818dc5583b8e6e765a 1 parent c75f9de
TJ Holowaychuk visionmedia authored

Showing 2 changed files with 31 additions and 2 deletions. Show diff stats Hide diff stats

  1. +22 2 index.js
  2. +9 0 test/index.js
24 index.js
... ... @@ -1,9 +1,15 @@
1 1
2 2 /**
  3 + * Current language.
  4 + */
  5 +
  6 +var lang = 'en';
  7 +
  8 +/**
3 9 * Expose `t`.
4 10 */
5 11
6   -module.exports = t;
  12 +exports = module.exports = t;
7 13
8 14 /**
9 15 * Translate the given `str` with substitions
@@ -17,7 +23,21 @@ module.exports = t;
17 23
18 24 function t(str, obj){
19 25 obj = obj || {};
  26 + if (t[lang]) str = t[lang][str] || str;
20 27 return str.replace(/\{([^}]+)\}/g, function(_, name){
21 28 return obj[name] || _;
22 29 });
23   -}
  30 +}
  31 +
  32 +/**
  33 + * Get / set language `code`.
  34 + *
  35 + * @param {String} code
  36 + * @return {String}
  37 + * @api public
  38 + */
  39 +
  40 +exports.lang = function(code){
  41 + if (0 == arguments.length) return lang;
  42 + lang = code;
  43 +};
9 test/index.js
@@ -12,4 +12,13 @@ describe('t(str)', function(){
12 12 t('{name} is {age} year(s) old', { name: 'Tobi', age: 2 })
13 13 .should.equal('Tobi is 2 year(s) old');
14 14 })
  15 +})
  16 +
  17 +describe('t.lang()', function(){
  18 + it('should utilize language definitions', function(){
  19 + t.es = { 'Hello {name}': 'Hola {name}' };
  20 + t.lang('es');
  21 + t.lang().should.equal('es');
  22 + t('Hello {name}', { name: 'Tobi' }).should.equal('Hola Tobi');
  23 + })
15 24 })

0 comments on commit 4e12b64

Please sign in to comment.
Something went wrong with that request. Please try again.