JSFiddle - React, Tailwind, and code Playground

by Sourabh Tewari

HTML

<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);