Given an array mapped in knockout.js and using custom templates, how can one have each item in the array rendered using a different template?
Here is a link to an example on jsFiddle of the desired functionality – somewhat as one would hope it would be.
In simple terms, given an array like this:
people: ko.observableArray([
{ name: 'Rod', age: 123, template: 'personItem' },
{ name: 'IBM', incorporated: 1911, template: 'corporateItem' },
])
How can one set up a foreach: binding that uses one template for some items, and different templates for others.
(Note: I am aware that the use of underscore templates somewhat conflates the issue in question, and apologize for any unnecessary confusion.)
I have thought about using one template with a set of if bindings – one for each template type, like this:
<div data-bind='foreach: people'>
<div data-bind='if: people.template() == "personItem"'>
</div>
<div data-bind='if: people.template() == "corporateItem"'>
</div>
</div>
This seems quite inelegant, and I suspect (hope) there is a more elegant and fairly straightforward option.
Any thoughts would be greatly appreciated & thanks for reading.
Rather than passing a string to the
nameparameter of thetemplatebinding, you can actually pass a function to determine the template. You would have to combine this with using theforeachoption in your case rather than doing an “each” through your items.So, your view model would look like:
and your mark up would be like:
Here is an example: http://jsfiddle.net/rniemeyer/xF2xe/
Here is some additional reference material:
http://www.knockmeout.net/2011/03/quick-tip-dynamically-changing.html
http://knockoutjs.com/documentation/template-binding.html#note_4_dynamically_choosing_which_template_is_used