Fork me on GitHub

BabelFish - i18n for node.js

![Build Status]1

Internationalisation with easy syntax for node.js. Classic solutions use multiple phrases for plurals. But we define plurals inline - that's more compact, and easier to maintain. Also, phrases are grouped into nested scopes, like in Ruby.

We support all pluralisation rules from unicode CLDR, version 2.0.1.

Phrases Syntax

  • #{varname} Echoes value of variable
  • ((Singular|Plural1|Plural2)):count Plural form

example:

А у меня в кармане #{nails_count} ((гвоздь|гвоздя|гвоздей)):nails_count

You can also omit anchor variable for plurals, by default it will be count. Thus following variants are equal:

  • I have #{count} ((nail|nails))
  • I have #{count} ((nail|nails)):count

Escape chars

If you need #{, ((, | or )) somewhere in text, where it can be considered as markup part - just escape them with \.

Example with YAML

As BabelFish supports scopes, it's really fun and nice to store translations in YAML files:

---
ru-RU:
  profile: Профиль
  forums: Форумы
  apps:
    forums:
      new_topic: Новая тема
      last_post:
        title : Последнее сообщение
        by : от
  demo:
    apples: "На столе лежит #{apples.count} ((яблоко|яблока|яблок)):apples.count"

Usage

// Create new instance of BabelFish with default language/locale: 'en-GB'
var i18n = require('babelfish').create('en-GB');


// Fill in some phrases
i18n.addPhrase('en-GB', 'demo.hello',         'Hello, #{user.name}.');
i18n.addPhrase('en-GB', 'demo.conv.wazup',    'Whats up?');
i18n.addPhrase('en-GB', 'demo.conv.alright',  'Alright, man!');

i18n.addPhrase('ru-RU', 'demo.hello',         'Привет, #{user.name}.');
i18n.addPhrase('ru-RU', 'demo.conv.wazup',    'Как дела?');

i18n.addPhrase('uk-UA', 'demo.hello',         'Здоровенькі були, #{user.name}.');


// Set locale fallback so we use most appropriate translation
i18n.setFallback('uk-UA', 'ru-RU');


// Translate
var params = {user: {name: 'ixti'}};

i18n.t('ru-RU', 'demo.hello', params);  // -> 'Привет, ixti.'
i18n.t('ru-RU', 'demo.conv.wazup');     // -> 'Как дела?'
i18n.t('ru-RU', 'demo.conv.alright');   // -> 'Alright, man!'

i18n.t('uk-UA', 'demo.hello', params);  // -> 'Здоровенькі були, ixti.'
i18n.t('uk-UA', 'demo.conv.wazup');     // -> 'Как дела?'
i18n.t('uk-UA', 'demo.conv.alright');   // -> 'Alright, man!'


// You may want to get "compiled" translations to export them into browser.
i18n.getCompiledData('ru-RU');
// -> {
//      'demo.hello'        : { type: 'function', translation: [Function] },
//      'demo.conv.wazup'   : { type: 'string', translation: 'Как дела?' },
//      'demo.conv.alright' : { type: 'string', translation: 'Alright, man!' }
//    }

NOTICE BabelFish#getCompiledData just exports an object with strings/functions. You are responsible to serialize it and then inject into browser runtime. Assuming that you have serialized data and it's available on browser as i18nData, you can do following to inject them into i18n (on browser):

<script type="text/javascript" src="/assets/babelfish-runtime.js"></script>
<script type="text/javascript" src="/assets/i18n.ru-RU.js"></script>
<script type="text/javascript">
  var i18n = new BabelFish('en-GB');

  // We assume `i18n.ru-RU.js` exports `i18nData` global variable
  i18n._storage['ru-RU'] = i18nData;
</script>

License

View the LICENSE file (MIT).

class

BabelFish

Description

Internalization and localization library that makes i18n and l10n fun again.

Example
var BabelFish = require('babelfish'),
    i18n = new BabelFish();

Constructor

Class methods

constructor

BabelFish.new

    • new BabelFish([defaultLocale = "en"])

Initiates new instance of BabelFish. It can't be used as function (without new keyword. Use create for this purpose.

class method

BabelFish.create

chainable
    • BabelFish.create([defaultLocale = "en"])

Syntax sugar for constructor:

new BabelFish('ru')
// equals to:
BabelFish.create('ru');
instance method

BabelFish#addPhrase

chainable
    • BabelFish#addPhrase(locale, phrase, translation)
    • locale
      • String
    • Locale of translation

    • phrase
      • String
      • Null
    • Phrase ID, e.g. apps.forum

    • translation
      • String
      • Object
    • Translation or an object with nested phrases.

Errors
  • TypeError when translation is neither String nor Object.
Example
i18n.addPhrase('ru-RU',
  'apps.forums.replies_count',
  '#{count} %{ответ|ответа|ответов}:count в теме');

// equals to:
i18n.addPhrase('ru-RU',
  'apps.forums',
  { replies_count: '#{count} %{ответ|ответа|ответов}:count в теме' });
instance method

BabelFish#getCompiledData

    • BabelFish#getCompiledData(locale, phrase)
      • Object
    • BabelFish#getCompiledData(locale)
      • Object
    • locale
      • String
    • Locale of translation

    • phrase
      • String
    • Phrase ID, e.g. app.forums.replies_count

Returns compiled "translator", or object with compiled translators for all phrases of locale if phrase was not specified.

Each translator is an object with fields:

  • type (String)

    • string: Simple translation (contains no substitutions)
    • function: Translation with macroses
  • locale (String|Null) Locale of translation. It can differ from requested locale in case when translation was taken from fallback locale.

  • translation (String|Function)

instance method

BabelFish#hasPhrase

    • BabelFish#hasPhrase(locale, phrase)
      • Boolean
    • locale
      • String
    • Locale of translation

    • phrase
      • String
    • Phrase ID, e.g. app.forums.replies_count

Returns whenever or not there's a translation of a phrase.

instance method

BabelFish#setFallback

chainable
    • BabelFish#setFallback(locale, fallbacks)
    • locale
      • String
    • Target locale

    • fallbacks
      • Array
    • List of fallback locales

Set fallbacks for given locale.

When locale has no translation for the phrase, fallbacks[0] will be tried, if translation still not found, then fallbacks[1] will be tried and so on. If none of fallbacks have translation, default locale will be tried as last resort.

Errors
  • throws Error, when locale equals default locale
Example
i18n.setFallback('ua-UK', ['ua', 'ru']);
instance method

BabelFish#t

    • BabelFish#t(locale, phrase[, params])
      • String
instance method

BabelFish#translate

    • BabelFish#translate(locale, phrase[, params])
      • String
    • locale
      • String
    • Locale of translation

    • phrase
      • String
    • Phrase ID, e.g. app.forums.replies_count

    • params
      • Object
    • Params for translation

Example
i18n.addPhrase('ru-RU',
  'apps.forums.replies_count',
  '#{count} %{ответ|ответа|ответов}:count в теме');

// ...

i18n.translate('ru-RU', 'app.forums.replies_count', {count: 1});
// -> '1 ответ'

i18n.translate('ru-RU', 'app.forums.replies_count', {count: 2});
// -> '2 ответa'
Aliased as: