Templates
Knockout's template system is incredibly flexible: it works with anonymous templates, named templates, and allows the engine that renders templates to be overridden. The template binding is also used by the foreach
binding, which is just a syntactic sugar for the { foreach: someExpression }
template. To understand how the template system works, let's start with the template-binding handler.
The template binding handler
The init
function of the template binding understands that templates can either be named (loaded from a source) or inline (loaded using the contents of the bound element):
'init': function(element, valueAccessor) { // Support anonymous templates var bindingValue = ko.utils.unwrapObservable(valueAccessor()); if (typeof bindingValue == "string" || bindingValue['name']) { // It's a named template - clear the element ko.virtualElements.emptyNode(element); } else { var templateNodes = ko.virtualElements.childNodes(element), container = ko.utils.moveCleanedNodesToContainerElement...