Ember.computed.collect as a template helper
MIT License
Ember.computed.collect
as a template helper
ember install ember-collect-helper
For detailed documentation, please view the API docs.
You have to imagine {{collect source paths}}
as the love child of
{{get}}
and Ember.computed.collect
.
In its simplest form, you pass a source
object and an array of paths
.
{{collect}}
will then return an array of the values from source
. Just as if
you would have called {{get source path}}
for every path of the paths
array.
{{collect
(hash
foo="bar"
quux="baz"
)
(array "quux" "foo")
}} => ['baz', 'bar']
The order you specified for paths
is kept.
You can also access arbitrarily deeply nested properties:
{{collect
(hash
foo="bar"
quux=(hash
quax="baz"
)
)
(array "quux.quax" "foo")
}} => ['baz', 'bar']
If a path is not defined, null
will be inserted in its place:
{{collect
(hash
foo="bar"
quux=(hash
quax="baz"
)
)
(array "quux.quax" "unknown" "foo")
}} => ['baz', null, 'bar']
If you want a defaultValue
other than null
, just specify it:
{{collect
(hash
foo="bar"
quux=(hash
quax="baz"
)
)
(array "quux.quax" "unknown" "foo")
defaultValue="oh no!"
}} => ['baz', 'oh no!', 'bar']
To make {{collect}}
a fully backwards compatible drop-in replacement for
{{get}}
, you can also pass just a string for paths
instead of an array of
strings.
{{collect (hash foo="bar") "foo"}} => 'bar'
{{collect (hash foo="bar") (array "foo")}} => ['bar']
In that case, the helper will not return an array with one value, but rather
only the value itself, just like {{get}}
would. This is especially useful,
when you're adding {{collect}}
to an existing code base and only need its
capabilities in isolated cases, that you enable by passing an array of paths
instead of a single path.
If you want to force {{collect}}
to return an array, you can pass wrapSingular=true
.
{{collect (hash foo="bar") "foo" wrapSingular=true}} => ['bar']