(work in progress)
i18n-js
You need a simple and objective javascript library for manipulating translations, regardless of web framework (AngularJS, React, Backbone.js, Ember.js, among others) or Node.JS? If your answer is yes, then read this document and see the resources available for this library.
Features
- Translation
- Interpolation
- Pluralization
- Aliases
Requirements
Installation
Server-side
In an environment with Node.js, install with NPM:
$ npm install i18n-js
Client-side
On your page, install with Bower:
$ bower install i18n-js
Usage
Before you start using the functionality provided by the library, first import it into your project:
Server-side
// Minimum configurationvar path = ;var i18n = urlTemplate: path locales: 'en-US' 'pt-BR' ;
Client-side
Then set the options that suit you best:
var i18n = ;
Now, create the translation files with the required texts, for example:
./locales/en-us.json
./locales/pt-br.json
./locales/es-es.json
Ready! With the default options, let's illustrate the use of the features:
Translation
Now, notice how simple the translation of a text:
// Common usei18n; // Customeri18n; // Cliente // Formal usei18n; // This field is requiredi18n; // Este campo é obrigatórioi18n; // Este campo é obrigatório // Multiple simultaneous translationsi18n; // { 'entry.firstname': 'Firstname', 'entry.lastname': 'Lastname' }i18n; // { 'entry.firstname': 'Nome', 'entry.lastname': 'Sobrenome' }i18n; // { 'entry.firstname': 'Nome', 'entry.lastname': 'Apellido', 'entry.customer': 'Customer' } // Translation from the fallback languagei18n; // Catalan translation => Spanish translation = Nombrei18n; // Deutsch translation => English translation = Firstname
Interpolation
Well, now that we know how the translation works, see how interpolate variables (variables replacement) with the translated text:
// Common usei18n; // Length must be between 1 and 15i18n; // O tamanho para este campo deve estar entre 1 e 15 i18n; // Welcome, Raphael!i18n; // Seja bem-vindo, Raphael! i18n; // My name is Raphael and I have 2 children.i18n; // Meu nome é Raphael e tenho 2 filhos. // Named parametersi18n; // Must be between 1 and 999i18n; // O valor para este campo deve estar entre 1 e 999
or, custom interpolator:
var vsprintf = vsprintf;var i18n = // Using sprintf to format { return /%/ ? : translatedText; }; i18n; // The first 4 letters of the english alphabet are: a, b, c and di18n; // As primeiras 4 letras do alfabeto Inglês são: a, b, c e d
Pluralization
The pluralization feature implemented in this library follows the specification defined in ICU User Guide, where its use is done as follows:
i18n; // No selected rowi18n; // 1 selected rowi18n; // 10 selected rows i18n; // Nenhuma linha selecionadai18n; // 1 linha selecionadai18n; // 10 linhas selecionadas
or, custom pluralizer:
var MessageFormat = ;var i18n = // Using message format for pluralization (override default pluralization) { var format = language; return ; }; i18n; // No records foundi18n; // 1 record foundi18n; // 10 records found
Aliases
After presentation of the main features of the library, we see an additional and very useful feature when you want to keep the semantics in your code:
// Default aliasesi18n; // Equivalent to i18n.get('error.required')i18n; // Equivalent to i18n.get('warn.timeout')i18n; // Equivalent to i18n.get('success.save')i18n; // Equivalent to i18n.get('info.changelog') // Custom aliasesi18n; // Create an alias 'text' for the namespace 'text.'i18ntext'welcome' 'Raphael'; // Equivalent to i18n.get('text.welcome', 'Raphael') i18n; // Create an alias 't' for the namespace 'text.'i18n; // Equivalent to i18n.get('text.welcome', 'Raphael')
API Reference
For a better understanding of the syntax and options supported by this library, read this section and see all the possibilities offered in their use:
i18n.get(translationId, [options])
Gets the corresponding translation to translation id.
Parameters
Param | Type | Details |
---|---|---|
translationId | String |
A JavaScript string as the translation key. |
options (optional) | Object |
If you need to send parameters to translated text interpolation or define how the translation should be done using the properties $lang , $count or $gender . |
Returns
- string - The translated text.
Usage
var vsprintf = vsprintf;var i18n = // preferred: 'en-US', // Default value fallbacks: 'ca': 'es-ES' 'en': 'en-US' 'pt-BR' // Not override the default interpolation { return /%/ ? : translatedText; }; // Translationi18n; // Demonstration of the use of I18n Node.JS libraryi18n; // Demonstração do uso da biblioteca I18n Node.JS i18n; // Firstnamei18n; // Nome i18n; // { 'entry.firstname': Firstname, 'entry.lastname': Lastname }i18n; // { 'entry.firstname': Nome, 'entry.lastname': Sobrenome } // Translation fallbacki18n; // Nombrei18n; // Firstname // Translation with default interpolationi18n; // Length must be no more than 255i18n; // O tamanho máximo para este campo é 255i18n; // Length must be between 1 and 255i18n; // O tamanho para este campo deve estar entre 1 e 255 i18n; // Percentage must be no more than 50i18n; // A porcentagem máxima para este campo é 50i18n; // Must be between 1 and 999i18n; // O valor para este campo deve estar entre 1 e 999 i18n; // Welcome, Raphael!i18n; // Seja bem-vindo, Raphael!i18n; // My name is Raphael and I am married to Elizabeth lady.i18n; // Meu nome é Raphael e sou casado com a senhora Elizabeth. i18n; // My name is Raphael.i18n; // Meu nome é Raphael.i18n; // My full name is Raphael Freitas.i18n; // Meu nome completo é Raphael Freitas. i18n; // My name is Raphael and I have 2 children.i18n; // Meu nome é Raphael e tenho 2 filhos.i18n; // My daughter's name is Isabelle and has only 3 years old.i18n; // O nome da minha filha é Isabelle e tem apenas 3 anos de idade. // Translation with custom interpolationi18n; // The first 4 letters of the english alphabet are: a, b, c and di18n; // As primeiras 4 letras do alfabeto Inglês são: a, b, c e d i18n; // Megan Fox, Beyoncé and Angelina Joliei18n; // Megan Fox, Beyoncé e Angelina Jolie // Translation with default pluralization (property $count is required)i18n; // No selected rowi18n; // 1 selected rowi18n; // 10 selected rows i18n; // Nenhuma linha selecionadai18n; // 1 linha selecionadai18n; // 10 linhas selecionadas // Translation with default aliases => e.g. i18n.error('required') equivalent to i18n.get('error.required')i18n; // This field is requiredi18n; // Este campo é obrigatório i18n; // Timeouti18n; // Tempo expirado i18n; // Successfully savedi18n; // Salvo com sucesso i18n; // Changelogi18n; // Log de alterações
i18n.setLocale(locale)
Sets the locale to be used in translation.
Parameters
Param | Type | Details |
---|---|---|
locale | String |
The locale to be used. |
Usage
i18n;
i18n.alias(name)
Sets an alias for a translation namespace.
Parameters
Param | Type | Details |
---|---|---|
name | String | Object |
The alias name to be used. |
Usage
i18n;i18ntext'welcome' 'Raphael'; // Equivalent to i18n.get('text.welcome') i18n;i18nlabel'firstname'; // Equivalent to i18n.get('entry.firstname')
Default aliases can not be overwritten.
i18n; // Equivalent to i18n.get('error.required')i18n; // Equivalent to i18n.get('warn.timeout')i18n; // Equivalent to i18n.get('success.save')i18n; // Equivalent to i18n.get('info.changelog')
Contributing
- Fork it ( https://github.com/raphaelfjesus/i18n-js/fork )
- Create your feature branch (
git checkout -b my-new-feature
) - Commit your changes (
git commit -am 'Add some feature'
) - Push to the branch (
git push origin my-new-feature
) - Create a new Pull Request
Tests
To run the test suite, first install the dependencies, then run npm test:
$ npm install$ npm test
License
The MIT License (MIT)
Copyright (c) 2016 Raphael F. Jesus raphaelfjesus@gmail.com
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.