BabelFish - human friendly i18n for JS
Internationalization with easy syntax for node.js and browser.
Classic solutions use multiple phrases for plurals. Babelfish
defines plurals
inline instead - that's more compact, and easy for programmers. Also, phrases
are grouped into nested scopes, like in Ruby.
BabelFish
supports all plural rules from unicode CLDR
(via plurals-cldr).
Installation
node.js:
$ npm install babelfish
browser:
$ bower install babelfish
Use es5-shim for old browsers
compatibility.
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
Also you can use variables in plural parts:
I have ((#{count} nail|#{count} nails))
Need special zero form or overwrite any specific value? No problems:
I have ((=0 no nails|#{count} nail|#{count} nails))
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 flatten 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: "На столе лежит #{count} ((яблоко|яблока|яблок))"
Usage
var BabelFish = require('babelfish');
var i18n = new BabelFish('en-GB');
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('en-GB', 'demo.coerce', 'Total: #{count}.');
i18n.addPhrase('ru-RU', 'demo.hello', 'Привет, #{user.name}.');
i18n.addPhrase('ru-RU', 'demo.conv.wazup', 'Как дела?');
i18n.addPhrase('uk-UA', 'demo.hello', 'Здоровенькі були, #{user.name}.');
i18n.setFallback('uk-UA', 'ru-RU');
var params = {user: {name: 'ixti'}};
i18n.t('ru-RU', 'demo.hello', params);
i18n.t('ru-RU', 'demo.conv.wazup');
i18n.t('ru-RU', 'demo.conv.alright');
i18n.t('uk-UA', 'demo.hello', params);
i18n.t('uk-UA', 'demo.conv.wazup');
i18n.t('uk-UA', 'demo.conv.alright');
i18n.t('en-GB', 'demo.coerce', 5);
var locale_dump = i18n.stringify('ru-RU');
var i18n_new = require('babelfish')('en-GB');
i18n_new.load(locale_dump);
i18n.addPhrase('en-GB', 'demo.boolean', true);
i18n.addPhrase('en-GB', 'demo.number', 123);
i18n.addPhrase('en-GB', 'demo.array', [1, 2, 3]);
i18n.addPhrase('en-GB', 'demo.array', { foo:1, bar:"2" }, false);
Implementations in other languages
License
View the LICENSE file (MIT).