View
<H1>People</H1><ulData-bind= "Template: {name: ' peoplelist '}"></ul><Scripttype= "text/html"ID= "Peoplelist"> <%_.each (People (),function(person) {%> <Li> <b Data-Bind="Text:person.name"></b> is <%= person.age%> years old </li> <% }) %></Script> <P>This shows the can use both Underscore-style evaluation (<%= ... %>)<em>and</em>Data-bind attributes in the same templates.</P>
ViewModel:
/*----Begin integration of underscore template engine with Knockout. Could go in a separate file of course. ---- */Ko.underscoretemplateengine=function() {} Ko.underscoreTemplateEngine.prototype= Ko.utils.extend (NewKo.templateengine (), {rendertemplatesource:function(Templatesource, BindingContext, options) {//precompile and cache the templates for efficiency varprecompiled = templatesource[' data ' (' precompiled ')); if(!precompiled) {Precompiled= _.template ("<% with ($data) {%>" + templatesource.text () + "<%}%>"); templatesource[' Data ' (' precompiled '), precompiled); } //Run the template and parse its output to an array of DOM elements varRenderedmarkup = Precompiled (BindingContext). Replace (/\s+/g, ""); returnko.utils.parseHtmlFragment (renderedmarkup); }, Createjavascriptevaluatorblock:function(script) {return"<%=" + script + "%>"; } }); Ko.settemplateengine (Newko.underscoretemplateengine ());/*----END integration of underscore template engine with Knockout----*/varViewModel ={People:ko.observableArray ([{name:' Rod ', age:123}, {name:' Jane ', age:125 }, ]) }; Ko.applybindings (ViewModel);
Using the underscore template in Knockout.js