2012-07-11 29 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