knockout templates #2
Using the “foreach” option with a named template
HTML
<h2>Employees</h2>
Here are the employees:
<!-- there'd be no need for mako here, the foreach does the job -->
<div data-bind="template: { name: 'person-template', foreach: employees }"></div>
<!-- there'd be no need for a foreach using mako -->
<script type="text/html" id="person-template">
<h4 data-bind="text: name"></h4>
<p>Credits: <span data-bind="text: credits"></span></p>
</script>
JavaScript
/* So what's going on here?
We have:
* a viewModel declaring three employees. Their name & credits
* a <div> for each template
* a template which has the html to be displayed
*/
function MyViewModel() {
var self = this;
self.employees = [
{ name: 'Frank', credits: 250 },
{ name: 'Bill', credits: 5800 },
{ name: 'John', credits: 5800 },
{ name: 'Fred', credits: 600 }
]
}
ko.applyBindings(new MyViewModel());