David W. Keith
David W. Keith

Reputation: 2254

How do I use localized strings in handlebar templates?

Say I had a view like:

<script type="text/x-handlebars" data-template-name="say-hello">
  Hello, <b>{{name}}</b>
</script>

How would I localize the word "Hello," using the built in Ember.String.loc()? I am not seeing a solution in the documentation/code.

Upvotes: 4

Views: 3196

Answers (1)

David W. Keith
David W. Keith

Reputation: 2254

I am now using built in localization.

To do so one would create a 'simple' view helper: http://gist.github.com/3093861:

Handlebars.registerHelper('loc', function(property, fn) {
  var str;
  // we are bound to a value, it is now the context
  if (fn.contexts && typeof fn.contexts[0] === 'string') {
    str = fn.contexts[0];

  // Convention, start all localization keys with _
  } else if (property[0] === '_') {
    str = property;

  // Convention, start all globals with capital
  } else if (/[A-Z]/.test(property[0])) {
    str = Em.getPath(window, property)

  // all other's are local properties
  } else {
    str = this.getPath(property)
  }

  return new Handlebars.SafeString((str || '').loc(''));
});

// use:
// {{loc _some_string}}
// {{#bind App.someString}}{{loc App.someString}}{{/bind}}
// {{#bind view.localString}}{{loc view.localString}}{{/bind}}

But this is not as clean as it should be, note how bound values need to be wrapped in {{#bind}}

Still open to better options. (I think I can update the view helper to support bindings, but have not investigated further yet)

Upvotes: 3

Related Questions