[英]How do you handle pluralisation in Ember?
是否有任何幫助使模板知道何時使用復數詞?
在下面的示例中,如何使模板輸出“2只狗......”?
編碼:
Ember.View.create({dog_count: 2})
模板:
{{dog_count}} (dog has)/(dogs have) gone for a walk.
我知道這已經過時了,但今天我需要它,所以這里有。
Ember.Handlebars.registerBoundHelper('pluralize', function(number, opts) {
var single = opts.hash['s'];
Ember.assert('pluralize requires a singular string (s)', single);
var plural = opts.hash['p'] || single + 's';
return (number == 1) ? single : plural;
});
用法:
{{questions.length}} {{pluralize questions.length s="Question"}}
要么
{{dog_count}} {{pluralize dog_count s="dog has" p="dogs have"}} gone for a walk.
只有當您不需要標准+ s行為時,才需要復數(p =)選項。
Ember有一個I18n庫: zendesk / ember-i18n 。
有一個把手幫助器t
通過從Em.I18n.translations
查找字符串來處理國際化:
Em.I18n.translations = {
'dog.walk.one': '1 dog has gone for a walk.',
'dog.walk.other': '{{count}} dogs have gone for a walk.'
};
然后,您可以通過以下方式在Handlebars模板中使用該字符串:
{{t dog.walk countBinding="dogCount"}}
上面的代碼未經測試,只是從README中的文檔中獲取。
我找到的另一個JS I18n庫是Alex Sexton的messageformat.js 。
這取決於你的應用程序的復雜性,但你也可以使用計算屬性,請參閱http://jsfiddle.net/pangratz666/pzg4c/ :
把手 :
<script type="text/x-handlebars" data-template-name="dog" >
{{dogCountString}}
</script>
JavaScript :
Ember.View.create({
templateName: 'dog',
dogCountString: function() {
var dogCount = this.get('dogCount');
var dogCountStr = (dogCount === 1) ? 'dog has' : 'dogs have';
return '%@ %@ gone for a walk.'.fmt(dogCount, dogCountStr);
}.property('dogCount')
}).append();
如果使用Ember Data,則可以使用Ember.Inflector
。
var inflector = new Ember.Inflector(Ember.Inflector.defaultRules);
inflector.pluralize('person') //=> 'people'
您可以注冊一個新的幫助:
Handlebars.registerHelper('pluralize', function(number, single) {
if (number === 1) { return single; }
else {
var inflector = new Ember.Inflector(Ember.Inflector.defaultRules);
return inflector.pluralize(single);
}
});
有關詳細信息,請訪問http://emberjs.com/api/data/classes/Ember.Inflector.html
看起來你從wycats那里得到了一個答案 ,但我沒有在這個帖子中看到它,所以這里是:
Handlebars.registerHelper('pluralize', function(number, single, plural) {
if (number === 1) { return single; }
else { return plural; }
});
我最近發現這個庫http://slexaxton.github.com/Jed/這似乎是JS i18n的一個很好的工具。 我想你可以通過使用這個庫注冊一個把手助手來輕松創建自己的實現。
我不知道任何Ember特定的功能會為你做這件事。 但是,通常在復數單詞時,單個版本僅在計數為1時顯示。
請看這個例子: http : //jsfiddle.net/6VN56/
function pluralize(count, single, plural) {
return count + " " + (count == 1 ? single : plural);
}
pluralize(1, 'dog', 'dogs') // 1 dog
pluralize(10, 'dog', 'dogs') // 10 dogs
pluralize(0, 'dog', 'dogs') // 0 dogs
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.