Skip to content

Instantly share code, notes, and snippets.

@amsul
Last active December 18, 2015 16:39
Show Gist options
  • Save amsul/5812749 to your computer and use it in GitHub Desktop.
Save amsul/5812749 to your computer and use it in GitHub Desktop.
Add the {{pluralize}} helper in Ember Handlebars templates.
// Register the pluralize helper.
Ember.Handlebars.registerBoundHelper( 'pluralize', function( number, options ) {
var phraseMatch = ( options.hash.phrase || '{|s}' ).match( /(.*?)\{(.*?)\|(.*?)\}/ )
Ember.assert( 'The optional "phrase" hash for {{pluralize}} should be formatted as <phrase to pluralize>{<singular ending>|<plural ending>}', phraseMatch )
var word = phraseMatch[ 1 ],
singular = word + phraseMatch[ 2 ],
plural = word + phraseMatch[ 3 ]
return number == 1 ? singular : plural
})
{{!
Basic usage
}}
{{ bananas_count }} banana{{ pluralize bananas_count }} in the bunch.
Singular: 1 banana in the bunch.
Plural: 5 bananas in the bunch.
{{!
Phrase usage
The syntax used for the "phrase" option is
<phrase to pluralize>{<singular ending>|<plural ending>}
}}
The {{ pluralize bananas_count phrase="banana{ is|s are}" }} on the table.
Singular: The banana is on the table.
Plural: The bananas are on the table.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment