Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you handle pluralisation in Ember?

Tags:

ember.js

Are there any helpers for making templates aware of when to use plural words?

In the example below, how do you make the template output "2 dogs have..."?

The code:

Ember.View.create({dog_count: 2})

The template:

{{dog_count}} (dog has)/(dogs have) gone for a walk.
like image 350
hekevintran Avatar asked May 29 '12 23:05

hekevintran


2 Answers

If you use Ember Data you can use Ember.Inflector.

var inflector = new Ember.Inflector(Ember.Inflector.defaultRules);

inflector.pluralize('person') //=> 'people'

You can register a new helper with:

Handlebars.registerHelper('pluralize', function(number, single) {
  if (number === 1) { return single; }
  else {
    var inflector = new Ember.Inflector(Ember.Inflector.defaultRules);
    return inflector.pluralize(single);
  }
});

More details at http://emberjs.com/api/data/classes/Ember.Inflector.html

like image 185
Giovanni Cappellotto Avatar answered Nov 04 '22 15:11

Giovanni Cappellotto


I know this is old, but I needed it today, so here goes.

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;
});

Usage:

{{questions.length}} {{pluralize questions.length s="Question"}}

or

{{dog_count}} {{pluralize dog_count s="dog has" p="dogs have"}} gone for a walk.

The plural (p=) option is only necessary when you don't want the standard +s behavior.

like image 23
tommyjr Avatar answered Nov 04 '22 15:11

tommyjr