Search code examples
handlebars.jsi18next

Variable replacement with i18next and handlebars


I've finally gotten my PhoneGap / Backbone / Handlebars to localize using i18next.js -- kind of.

I'm currently wondering how to get html with embedded handlebars expressions to both localize and compile with Handlebars. As an example, I want something like this:

Welcome, {{this.name}}. We've been expecting you.

to turn into:

Welcome, Bob. We've been expecting you.

That's easy enough without localization. But run through the i18next template described in the docs (here: http://i18next.com/pages/doc_templates.html)...

// handlebars helper from i18next
Handlebars.registerHelper('t', function(i18n_key) {
  var result = i18n.t(i18n_key);
  return new Handlebars.SafeString(result);
});

//Handlebars string:
{{t 'view.WelcomeMessage'}}

// translation.json file
{ "view":
    {
        "WelcomeMessage": "Welcome, {{this.name}}. We've been expecting you."
    }
}

Unfortunately, this turns into the following when localized:

Welcome, {{this.name}}. We've been expecting you.

How do I get the string to localize and have embedded expression compile?


Solution

  • It looks like the the answer for this is in the variable replacement helper tr:

    // handlebars helper from i18next
    Handlebars.registerHelper('tr', function(context, options) { 
      var opts = i18n.functions.extend(options.hash, context);
      if (options.fn) opts.defaultValue = options.fn(context);
      var result = i18n.t(opts.key, opts);
      return new Handlebars.SafeString(result);
    });
    
    // random "This" object passed in:
    var person = {name:"Bob", age:42, eyeColor:"blue"};
    
    //Handlebars string:
    {{tr this key='view.WelcomeMessage'}}
    
    // translation.json file
    { "view":
      {
        "WelcomeMessage": "Welcome, __name__. We've been expecting you."
      }
    }
    
    // Output
    Welcome, Bob. We've been expecting you.
    

    Note that the tr example given on http://i18next.com/pages/doc_templates.html does have an extra parameter at the end. This is only necessary if you want to replace one of the this attributes with something else.