繁体   English   中英

你如何处理Ember的多元化?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM