<script src="http://documentcloud.github.com/underscore/underscore-min.js"></script>
<h1>People and Corporations</h1>
<ul data-bind="template: { name: getTemplate, foreach: people }"></ul>
<script type="text/html" id="personItem">
<li>
<b data-bind="text: name"></b> is <%= age %> years old
</li>
</script>
<script type="text/html" id="corporateItem">
<li>
<b data-bind="text: name"></b> is <%= incorporated %> years old
</li>
</script>
JavaScript
/* ---- 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(new ko.templateEngine(), {
renderTemplateSource: function (templateSource, bindingContext, options) {
// Precompile and cache the templates for efficiency
var precompiled = templateSource['data']('precompiled');
if (!precompiled) {
precompiled = _.template("<% with($data) { %> " + templateSource.text() + " <% } %>");
templateSource['data']('precompiled', precompiled);
}
// Run the template and parse its output into an array of DOM elements
var renderedMarkup = precompiled(bindingContext).replace(/\s+/g, " ");
return ko.utils.parseHtmlFragment(renderedMarkup);
},
createJavaScriptEvaluatorBlock: function(script) {
return "<%= " + script + " %>";
}
});
ko.setTemplateEngine(new ko.underscoreTemplateEngine());
/* ---- End integration of Underscore template engine with Knockout ---- */
var viewModel = {
people: ko.observableArray([
{ name: 'Rod', age: 123, template: 'personItem' },
{ name: 'IBM', incorporated: 1911, template: 'corporateItem' },
]),
getTemplate: function(item) {
return item.template;
}
};
ko.applyBindings(viewModel);
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.