I’m writing a toSentence
helper that will take an array of items (say, people
) and an attribute name (say firstName
), and build a “sentence” out of it. For example:
With
people = [Em.Object.create(firstName: 'Pedro'), Em.Object.create(firstName: 'Pablo'), Em.Object.create(firstName: 'Diego')]
then
{{toSentence people attr=firstName}}
outputs
Pedro, Pablo and Diego
This works until one of the object’s firstName (or whatever attribute) changes, since the helper has no dependent keys. To fix this, when defining the helper I would have to add the dependent keys, like so:
Ember.Handlebars.helper 'toSentence', (thefunction), '@each.firstName'
But this ONLY works for the firstName attribute… How can I make that key “dynamic”? Or am I approaching this the wrong way?
For completion’s sake, here’s the entire toSentence
helper:
Ember.Handlebars.helper 'toSentence', (items, options) ->
array = items.toArray().map (item) ->
if options.hash.attr?
Handlebars.Utils.escapeExpression(item.get(options.hash.attr))
else
Handlebars.Utils.escapeExpression(item.toString())
sentence = if array.length == 0
""
else if array.length == 1
"#{array[0]}"
else if array.length == 2
"#{array[0]}, #{array[1]}"
else
"#{array[0..-2].join(', ')} and #{array[array.length-1]}"
new Handlebars.SafeString(sentence)