Skip to content

i18n Internationalisation

claustres edited this page Jul 15, 2015 · 4 revisions

By using AngularJS the most appropriate option seems to be https://angular-translate.github.io/. What is interesting with it, in addition to its features, is the possibility to use it as a service (to translate strings inside the code) or as a filter/directive to directly manage translation at the view level (avoiding binding your translation too hard to controllers).

We already implemented it in a MEAN.IO stack on a project where we have a 'core' package configuring it like this:

angular.module('mean.core')
    .config(['$httpProvider', '$translateProvider', function($httpProvider, $translateProvider){
        $translateProvider.useLocalStorage();
        $translateProvider.determinePreferredLanguage();
        $translateProvider.fallbackLanguage(['fr_FR']);
        $translateProvider.useLoader('$translatePartialLoader', {
            urlTemplate: '{part}/i18n/{lang}.json'
        });
    }])

This means that the translations will not be given as a big key-value map for each langage but in separate pieces (i.e. 'parts'). These parts will be looked for in the part-name/i18n folder, one JSON file per langage. The most simple way to implement it is to have one part per MEAN.IO module, containing all the translations of the module. Then, you declare the translations of a module (e.g. 'gui') like this:

angular.module('mean.gui')
    .config(['$translatePartialLoaderProvider', function($translatePartialLoaderProvider){
        $translatePartialLoaderProvider.addPart('gui');
    }]);

The translation object of the module looks like this (e.g. file i18n/fr_FR.json of the module):

{
  "gui": {
	"ABOUT_APP": "A propos de l'application",
	...
  }
}

You use a translation of the module in a view like this:

<div class="jumbotron">
    <div class="row">
        <h2 class="col-xs-12">{{'gui.ABOUT_APP' | translate}}</h2>
    </div>
    <div class="row" ng-transclude></div>
</div>

And in the code like this:

  // Modal confirmation
  return $translate('gui.ITEM_DELETED_WARNING').then(function(translation){
       return DialogService.confirm({
            text: translation + this.service.objectType
        }).then(function () {
            this.remove(item);
        }.bind(this));
    }.bind(this));
Clone this wiki locally