Simplistic I18N tool for universal/isomorphic Javascript.
Usage with RequireJS
To use with RequireJS I'd advise to also use the plugin requirejs-i18njs to be able to precompile the templates that are in your translation files for your production code.
Usage with Handlebars
You can register your helper simply by using the .get()
function of i18njs
Handlebars;
then in your templates :
// Arguments after the 'key' are optionalsi18n 'key' data options lang
Installation
Either
npm install --save i18njs
or
bower install --save i18njs
Usage
Import it the way you want into your project :
// CommonJSvar i18njs = ;
// AMD;
// Global
Add locales
Your localized strings are simple json objects.
Namespaces can be as deep as you need.
var en_locales = 'hello_world': 'hello': 'Hello' 'world': 'World' ; var fr_locales = 'hello_world': 'hello': 'Bonjour' 'world': 'Monde' ; // i18n.add(language, [namespace,] locales);i18n;i18n;
Change language
By default, language is set to en
.
i18n;
Get current language
i18n;
Get dictionary
i18n;
Check for availability
If needed, you can also check for the presence of a specific localized string in a particular language.
You can check only the language too.
// i18n.has([key,] lang)i18n;// true i18n;// true i18n;// true i18n; // false i18n; // false i18n; // false
List available languages
i18n;// ['en', 'fr']
Get basic localized string
// i18n.get(key[, data, options][, lang]);i18n;// Hello i18n;// Bonjour
Get templated string
It uses a basic templating engine, the same as underscore.
It works in the form of {{=interpolate}}
, {{evaluate}}
or {{-escape}}
:
// localized stringsvar en_locales = 'st': '{{=interpolate}}{{for(var i = 0, max = 5; i < max; i += 1) {}} to{{}}} {{-escape}}'; // context used in the templated stringvar data = 'interpolate': 'Hello' 'escape': '\'<the>\' `&` "World"'; // register the localized stringi18n; // give it a context with the data objectvar st = i18n;// "Hello to to to to to '<the>' `&` "World""
Change delimiters
You can also change delimiters by passing the third options
arguments
var st = i18n;
Will result in these delimiters <%=interpolate%>
, <%evaluate%>
or <%-escape%>
Add default values for templates
If you need to have a special key always replaced by the same value (a brand for example), you can set it as a default.
This key
will be then replaced across your application's localized strings and you
won't need to pass it as a context object to your .get()
.
var fr = welcome: 'Bienvenue sur {{=brand}}'; var en = welcome: 'Welcome to {{=brand}}'; var defaults = fr: brand: 'Ma Marque' en: brand: 'My Brand' ; i18n;i18n;i18n; i18n;//Welcome to My Brandi18n;// My Brand
You don't have to use localized defaults if you don't need to :
var defaults = brand: 'My Brand'; i18n;i18n; i18n;//Bienvenue sur My Brand
You can also check your defaults :
i18n;//{// brand: 'My Brand',// fr: {// brand: 'Ma Marque'// },// en: {// brand: 'My Brand'// }//}