Localizing templates using require.js, backbone and underscore

backbone.js, localization, requirejs, templates, underscore.js

Solution

For completeness, the solution that we came up that felt to most optimised was:

When a template was requested from the server, a cookie determined the language and the correct template was delivered.

Used PHP back end to pre-parse the templates; these were then stored in memcached in the correct language

The language template, once requested, was then cached by the browser and internally in a backbone model so it could be rapidly re-used by JavaScript.

Reasons:

- faster JS (far fewer regular expression replaces). We never benchmarked, but it is only logical when you remove the functions completely.

- saved transferring a HUGE language file to the client

Problem

This question is about templating and localizing, using require.js and underscore templates through backbone.js. The application will need to be localised on the fly. Before embarking down a path that later proved problematic, is there a better solution than the one I'm considering - I'm concerned about speed and memory with repeatedly merging and processing the language array. Assume that are a 2-3 thousand language strings. Current approach (which works, but looks processor heavy): - Using the I18N bundling approach, create language "includes" that will essentially contain the translated elements for all the templates - Merge this object/array of elements with model attributes (from backbone) and pass the merged lot into the underscore template . ``` define(['backbone', 'models/model', 'text!template.html', 'i18n!my/nls/translatedbits'], function(Backbone, MyModel, TemplateText, TranslationObject) { var View = Backbone.View.extend({ model: {}, initialize : function(params) { this.model = new MyModel(); }, render : function(callBack) { // Get the model attributes var templateParams = _.clone(this.model.attributes); // Bolt on the tranlsated elements (established from require.js I18N plugin) templateParams.t = TranslationObject; // Pass the lot ot the template var template = _.template(TemplateText, this.model.attributes); $(this.el).html( template ); return this; } }); return View; } ); ``` Then the template will read ``` <%= modelAttribute1 %> <%= t.translationString1 %> ``` Is there a better solution or a better templating engine? [Better for this purpose - mustache may have other advantages, but can it localize more easily, or can it cache localised results allowing model attributes to be passed in later?] Note that languages may need to be changed "on the fly" - and that's another concern I have with I18N plugin. I may end up getting the transations by JSON request through a template model but this still requires a merge of objects, which is what I'm trying to avoid.

Original source