All samples are using Ink.requireModules, please read how to use it at Ink.requireModules section

Ink.Util.I18n class

You can use this module to internationalize your applications. It roughly emulates GNU gettext's API.

Methods
Method name Description
new I18n(dict, [lang], [testMode]) Constructor
.alias() Create an alias.
.append(dict) Adds translation strings for the helper to use.
.appendGlobal(dict, lang) Adds a dictionary to be used in all I18n instances for the corresponding language.
.getKey(key) Gest a key from the current dictionary
.lang([lang]) Gets or sets the language.
.langGlobal([lang]) Gets or sets the current default language of I18n instances.
.ntext(strSin, strPlur, count) Translates and pluralizes text.
.ordinal(num, [options]) Gets the ordinal suffix of a number.
.reset() Resets I18n global state (global dictionaries, and default language for instances)
.testMode([newTestMode]) Sets or unsets test mode.
.text(str, [namedParms], [args], [arg2]) Translates a string.

new Ink.Util.I18n(dict, [lang], [testMode])

Accepts

  • dict

    Object mapping language codes (in the form of `pt_PT`, `pt_BR`, `fr`, `en_US`, etc.) to their `dictionaries`
  • lang

    'pt_PT'language code of the target language
  • testMode

    falseSets the test mode (see `testMode()`) on construction.

Some API functions

Code

var dictionaries = {    // This could come from a JSONP request from your server
    'pt_PT': {
        'hello': 'olá',
        'me': 'eu',
        'i have a {} for you': 'tenho um {} para ti' // Old syntax using `{%s}` tokens still available
    },
    'pt_BR': {
        'hello': 'oi',
        'me': 'eu',
        'i have a {} for you': 'tenho um {} para você'
    }
};
Ink.requireModules(['Ink.Util.I18n_1'], function (I18n) {
    var i18n = new I18n(dictionaries, 'pt_PT');
    i18n.text('hello');  // returns 'olá'
    i18n.text('i have a {} for you', 'IRON SWORD'); // returns 'tenho um IRON SWORD' para ti
    
    i18n.lang('pt_BR');  // Changes language. pt_BR dictionary is loaded
    i18n.text('hello');  // returns 'oi'

    i18n.lang('en_US');  // Missing language.
    i18n.text('hello');  // returns 'hello'. If testMode is on, returns '[hello]'
});

// The old {%s} syntax from libsapo's i18n is still supported
i18n.text('hello, {%s}!', 'someone'); // -> 'olá, someone!'

.alias() method

Create an alias.

Returns an alias to this I18n instance. It contains the I18n methods documented here, but is also a function. If you call it, it just calls text(). This is commonly assigned to "_".

var i18n = new I18n({
    'pt_PT': {
        'hi': 'olá',
        '{} day': '{} dia',
        '{} days': '{} dias',
        '_ordinals': {
            'default': 'º'
        }
    }
}, 'pt_PT');
var _ = i18n.alias();
_('hi');  // -> 'olá'
_('{} days', 3);  // -> '3 dias'
_.ntext('{} day', '{} days', 2);  // -> '2 dias'
_.ntext('{} day', '{} days', 1);  // -> '1 dia'
_.ordinal(3);  // -> 'º'

.append(dict) method

Adds translation strings for the helper to use.

Accepts

  • dict

    Object containing language objects identified by their language code
var i18n = new I18n({}, 'pt_PT');
i18n.append({'pt_PT': {
    'sfraggles': 'braggles'
}});
i18n.text('sfraggles') // -> 'braggles'

.appendGlobal(dict, lang) method

Adds a dictionary to be used in all I18n instances for the corresponding language.

Accepts

  • dict

    Dictionary to be added
  • lang

    Language fo the dictionary being added

.getKey(key) method

Gest a key from the current dictionary

Accepts

  • key

    Key you wish to get from the dictionary.
_.getKey('astring'); // -> 'a translated string'
_.getKey('anobject'); // -> {'a': 'translated object'}
_.getKey('afunction'); // -> function () { return 'this is a localized function' }

.lang([lang]) method

Gets or sets the language.
If there are more dictionaries available in cache, they will be loaded.

Accepts

  • lang

    Language code to set this instance to. Omit this argument if you want to get the language code instead.

.langGlobal([lang]) method

Gets or sets the current default language of I18n instances.

Accepts

  • lang

    the new language for all I18n instances. Omit this argument if you wish to *get* the current default language instead.

.ntext(strSin, strPlur, count) method

Translates and pluralizes text.
Given a singular string, a plural string and a number, translates either the singular or plural string.

Accepts

  • strSin

    Word to use when count is 1
  • strPlur

    Word to use otherwise
  • count

    Number which defines which word to use
  • args...

    Extra arguments, to be passed to `text()`
i18n.ntext('platypus', 'platypuses', 1); // returns 'ornitorrinco'
i18n.ntext('platypus', 'platypuses', 2); // returns 'ornitorrincos'

// The "count" argument is passed to text()
i18n.ntext('{} platypus', '{} platypuses', 1); // returns '1 ornitorrinco'
i18n.ntext('{} platypus', '{} platypuses', 2); // returns '2 ornitorrincos'

.ordinal(num, [options]) method

Gets the ordinal suffix of a number.

This works by using transforms (in the form of Objects or Functions) passed into the function or found in the special key _ordinals in the active language dictionary.

Accepts

  • num

    Input number
  • options

    {}Dictionaries for translating. Each of these options' fallback is found in the current language's dictionary. The lookup order is the following: `exceptions`, `byLastDigit`, `default`. Each of these may be either an `Object` or a `Function`. If it's a function, it is called (with `number` and `digit` for any function except for byLastDigit, which is called with the `lastDigit` of the number in question), and if the function returns a string, that is used. If it's an object, the property is looked up using `obj[prop]`. If what is found is a string, it is used directly.
  • options.byLastDigit

    {}If the language requires the last digit to be considered, mappings of last digits to ordinal suffixes can be created here.
  • options.exceptions

    {}Map unique, special cases to their ordinal suffixes.
var i18n = new I18n({
    pt_PT: {  // 1º, 2º, 3º, 4º, ...
        _ordinal: {  // The _ordinals key each translation dictionary is special.
            'default': "º" // Usually the suffix is "º" in portuguese...
        }
    },
    fr: {  // 1er, 2e, 3e, 4e, ...
        _ordinal: {  // The _ordinals key is special.
            'default': "e", // Usually the suffix is "e" in french...
            exceptions: {
                1: "er"   // ... Except for the number one.
            }
        }
    },
    en_US: {  // 1st, 2nd, 3rd, 4th, ..., 11th, 12th, ... 21st, 22nd...
        _ordinal: {
            'default': "th",// Usually the digit is "th" in english...
            byLastDigit: {
                1: "st",  // When the last digit is 1, use "th"...
                2: "nd",  // When the last digit is 2, use "nd"...
                3: "rd"   // When the last digit is 3, use "rd"...
            },
            exceptions: { // But these numbers are special
                0: "",
                11: "th",
                12: "th",
                13: "th"
            }
        }
    }
}, 'pt_PT');

i18n.ordinal(1);    // returns 'º'
i18n.ordinal(2);    // returns 'º'
i18n.ordinal(11);   // returns 'º'

i18n.lang('fr');
i18n.ordinal(1);    // returns 'er'
i18n.ordinal(2);    // returns 'e'
i18n.ordinal(11);   // returns 'e'

i18n.lang('en_US');
i18n.ordinal(1);    // returns 'st'
i18n.ordinal(2);    // returns 'nd'
i18n.ordinal(12);   // returns 'th'
i18n.ordinal(22);   // returns 'nd'
i18n.ordinal(3);    // returns 'rd'
i18n.ordinal(4);    // returns 'th'
i18n.ordinal(5);    // returns 'th'

.reset() method

Resets I18n global state (global dictionaries, and default language for instances)

.testMode([newTestMode]) method

Sets or unsets test mode.
In test mode, unknown strings are wrapped in [ ... ]. This is useful for debugging your application and to make sure all your translation keys are in place.

Accepts

  • newTestMode

    Flag to set the test mode state. Omit this argument to *get* the current testMode instead.

.text(str, [namedParms], [args], [arg2]) method

Translates a string.
Given a translation key, return a translated string, with replaced parameters.
When a translated string is not available, the original string is returned unchanged.

Accepts

  • str

    Key to look for in i18n dictionary (which is returned verbatim if unknown)
  • namedParms

    Named replacements. Replaces {named} with values in this object.
  • args

    Replacement #1 (replaces first {} and all {1})
  • arg2

    Replacement #2 (replaces second {} and all {2})
  • argn...

    Replacement #n (replaces nth {} and all {n})
_('Gosto muito de {} e o céu é {}.', 'carros', 'azul');
// returns 'Gosto muito de carros e o céu é azul.'

_('O {1} é {2} como {2} é a cor do {3}.', 'carro', 'azul', 'FCP');
// returns 'O carro é azul como azul é o FCP.'

_('O {person1} dava-se com a {person2}', {person1: 'coisinho', person2: 'coisinha'});
// -> 'O coisinho dava-se com a coisinha'

// This is a bit more complex
var i18n = new Ink.Util.I18n().lang('pt_PT').append({
    pt_PT: {
        array: [1, 2],
        object: {'a': '-a-', 'b': '-b-'},
        func: function (a, b) {return '[[' + a + ',' + b + ']]';}
    }
});
i18n.text('array', 0); // -> '1'
i18n.text('object', 'a'); // -> '-a-'
i18n.text('func', 'a', 'b'); // -> '[[a,b]]'