2012-07-11 54 views
4

说我有过一个观点:如何在车把模板中使用本地化的字符串?

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

我将如何本地化单词“你好”,使用内置Ember.String.loc()?我没有在文档/代码中看到解决方案。

+2

您可能想看看[ember-i18n](https://github.com/zendesk/ember-i18n)项目或[i18n-js](https://github.com/fnando/i18n-js) – MilkyWayJoe 2012-07-11 20:27:15

+0

嗯,似乎很重,为什么我不写一个简单的本地化帮手: – 2012-07-11 21:45:52

+4

@MilkyWayJoe本地化助手:https:// gist.github.com/3093861 – 2012-07-11 21:51:34

回答

3

我现在正在使用内置本地化。

这样做一会创建一个“简单”的视图助手: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}} 

但是,这并不干净,因为它应该是,注意需要值如何绑定到被包裹在{{#bind}}

仍然向更好的选择开放。 (我想我可以更新视图帮助器来支持绑定,但还没有进一步调查)

+0

我正在处理类似的问题ATM。我使用了一些服务器端模板(英文模板带有额外的标记,以便单独的工具可以提取英文,并根据需要用翻译版本替换它)。请记住,你不能只翻译“你好”并将它粘贴在名字上,你必须翻译整个句子。 – 2012-07-19 18:34:02

+0

是的,这是我的解决方案无法解决的另一个问题。我将需要一种方法来格式化未来的本地化字符串,并且需要考虑在那个时候更新助手。 – 2012-07-20 16:27:15