Content internalization and localization (i18n) with Backbone and Mustache
- Translation specific elements in Mustache templates;
- Global access to the translations through Javascript variables;
- Request the translations from an external API;
- Script Tag:
<script type="text/javascript" src="http://cdn.rawgit.com/Cloudoki/backbone-i18n/master/index.js"></script>
- Bower:
bower install git://github.com/Cloudoki/backbone-i18n.git
- npm:
npm install github:Cloudoki/backbone-i18n
// Define your translations
var translations = {
'Hello World!': 'Olá Mundo!'
};
var i18n = new I18n(); // Initialize the translations plugin
i18n.set(translations); // Apply the translations
After initializing the plugin, the translations will be automatically hooked up to Mustache:
var template = "{{#_i18n_}}{{title}}{{/_i18n_}}";
this.$el.html(Mustache.render( template, {title: 'Hello World!'})); // Render
You can also access the translations through Javascript variables:
console.log(i18n.translate('Hello World!')); // Olá Mundo!
console.log(i18n.translate('lost in translation')); // lost in translation
// You will need to extend the i18n Backbone Model
// to provide the translations resource url
var xi18n = I18n.extend({
url: function(){
return '/translations/' + this.locale ? this.locale : 'en-GB';
}
});
var i18n = new xi18n();
i18n.setLocale('pt-PT');
i18n.fetch({
success: function(){
console.log('translations loaded');
},
});
You will need a static server
npm install -g http-server
Serve the entire project directory
http-server ./
Open your browser at http://127.0.0.1:8080/examples/