• Stars
    star
    250
  • Rank 156,379 (Top 4 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 12 years ago
  • Updated 11 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

human friendly i18n for javascript (node.js + browser)

BabelFish - human friendly i18n for JS

CI NPM version Coverage Status

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

// Create new instance of BabelFish with default language/locale: 'en-GB'
var BabelFish = require('babelfish');
var i18n = new BabelFish('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('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}.');


// Set locale fallback to use the most appropriate translation when possible
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!'

// When params is number or strings, it will be coerced to
// `{ count: XXX, value: XXX }` - use any of those in phrase.
i18n.t('en-GB', 'demo.coerce', 5);      // -> 'Total: 5.'


// You may wish to "dump" translations to load in browser later
// Dump will include all fallback translations and fallback rules
var locale_dump = i18n.stringify('ru-RU');

var i18n_new = require('babelfish')('en-GB'); // init without `new` also works
i18n_new.load(locale_dump);


// Use objects instead of strings (object/array/number/boolean) - can be
// useful to prepare bulk data for external libraries.
// Note, only JSON-supported types are ok (no date & regex)
i18n.addPhrase('en-GB', 'demo.boolean',  true);
i18n.addPhrase('en-GB', 'demo.number',   123);
i18n.addPhrase('en-GB', 'demo.array',    [1, 2, 3]);
// fourth param required for hashes (objects) to disable flattening,
// other types are autodetected
i18n.addPhrase('en-GB', 'demo.array',    { foo:1, bar:"2" }, false);

Implementations in other languages

License

View the LICENSE file (MIT).

More Repositories

1

js-yaml

JavaScript YAML parser and dumper. Very fast.
JavaScript
6,185
star
2

pako

high speed zlib port to javascript, works in browser & node.js
JavaScript
5,328
star
3

pica

Resize image in browser with high quality and high speed
JavaScript
3,612
star
4

probe-image-size

Get image size without full download. Supported image types: JPG, GIF, PNG, WebP, BMP, TIFF, SVG, PSD, ICO.
JavaScript
957
star
5

argparse

CLI arguments parser for node.js. JS port of python's argparse module.
JavaScript
484
star
6

image-blob-reduce

Resize image blobs with high quality. Pica's wrapper to work with file inputs.
JavaScript
245
star
7

tabex

Cross-tab message bus for browsers.
JavaScript
220
star
8

url-unshort

Short links expander for node.js
JavaScript
112
star
9

ndoc

js port of pdoc, with extentions
JavaScript
100
star
10

charlatan

Fake identities generator for node.js (names, addresses, phones, IPs and others). Supports multiple languages.
JavaScript
95
star
11

nodeca

Forums / Blogs / Groups / Classfields / ... platform. Fork this to make your own config.
JavaScript
94
star
12

bag.js

JS / CSS / files loader + key/value storage
JavaScript
88
star
13

idoit

Redis-backed task queue engine with advanced task control and eventual consistency
JavaScript
72
star
14

glur

Fast gaussian blur in pure JavaScript via IIR filer
JavaScript
68
star
15

multimath

WebAssembly wrapper to simplify fast math coding
JavaScript
66
star
16

embedza

Create HTML snippets/embeds from URLs using info from oEmbed, Open Graph, meta tags.
JavaScript
62
star
17

promise-memoize

Memoize promise-returning functions. Includes cache expire and prefetch.
JavaScript
58
star
18

navit

Simple client testing from your scripts
JavaScript
47
star
19

unhomoglyph

Replace all homoglyphs with base characters. Useful to detect similar strings.
JavaScript
38
star
20

nntp-server

NNTP server for readers
JavaScript
26
star
21

puncher

Library to set timestamps in your application requests & genegate profiling tree.
JavaScript
13
star
22

eslint-plugin-nodeca

Indentation check rule for ESLint
JavaScript
12
star
23

nodeca.core

Nodeca core app (admin panel, loader, bundler)
JavaScript
11
star
24

types

Collection of extra types (structures, classes) for JavaScript.
JavaScript
10
star
25

nodeca.users

Nodeca user app (login / register / albums / profiles)
JavaScript
10
star
26

event-wire

Mediator with dynamic responsibility chains
JavaScript
9
star
27

hike-js

Javascript port of Hike (Ruby) - a library for finding files in a set of paths
JavaScript
9
star
28

plurals-cldr

Plurals suport for JS, autogenerated from CLDR.
JavaScript
8
star
29

relimit

Rate limiter with tuneable scheduler and distributed run support
JavaScript
8
star
30

js-yaml-js-types

Extra js types for js-yaml
JavaScript
7
star
31

mimoza

Simple mime-type tools library
JavaScript
7
star
32

pointer

router for node.js / client
JavaScript
6
star
33

nodeca.forum

Nodeca forum app
JavaScript
3
star
34

redis-if

JavaScript
3
star
35

nodeca-design

Nodeca interface mockups
HTML
3
star
36

fontomas

2
star
37

nodeca.blogs

Blogs component for Nodeca
JavaScript
2
star
38

nodeca.clubs

Clubs component for Nodeca
JavaScript
2
star
39

nodeca.market

Market component for Nodeca
JavaScript
1
star
40

charcount

Count visual length of javascript string
JavaScript
1
star