title: Localizing templates using require.js, backbone and underscore
body: <p>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.</p>
  
  <p>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.</p>
  
  <p>Current approach (which works, but looks processor heavy):</p>
  
  <ol>
  <li>Using the <a href="http://requirejs.org/docs/api.html#i18n">I18N bundling approach</a>, create language "includes" that will essentially contain the translated elements for all the templates</li>
  <li>Merge this object/array of elements with model attributes (from backbone) and pass the merged lot into the underscore template</li>
  </ol>
  
  <p>.</p>
  
  <pre><code>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;
    }
  );
  </code></pre>
  
  <p>Then the template will read </p>
  
  <pre><code>&lt;%= modelAttribute1 %&gt; &lt;%= t.translationString1 %&gt;
  </code></pre>
  
  <p>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?] </p>
  
  <p>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.</p>