Search code examples
knockout.jsjquery-templates

Knockout native templates equivalent to the jQuery .tmpl(data) function


I am currently migrating my knockout.js app from using the jQuery tmpl library to use the native knockout templating library. One of the lines of code I have to migrated is:

$("#someTemplate").tmpl(data.SomeDataFromServer).appendTo(someHtmlElement); 

The tmpl() function is obviously part of the jQuery tmpl library (see http://api.jquery.com/tmpl/)

Given I have now changed my template to:

    <script id="someTemplate" type="text/html">
        <li>
            ... some cooling stuff using native ko templates ;-) 
        </li>
    </script>

... what would the new call to the template look like?


Solution

  • You would use the template binding like:

    <div data-bind="template: 'someTemplate'"></div>
    

    or

    <div data-bind="template: { name: 'someTemplate', foreach: myItems }"></div>
    

    or

    <div data-bind="template: { name: 'someTemplate', data: SomeDataFromServer }"></div>
    

    This works with native templates as well as jQuery Templates. If you are only using jQuery templates, then make sure that you are not referencing the jQuery Templates plugin.

    If your data is an observable, then initially it can be null and nothing will get rendered. Then, when you populate it from an AJAX call then it will be updated with your data.

    Another option is to use ko.applyBindingsToNode, which would look like:

    var data = [ { name: "one" }, { name: "two" } ];
    
    ko.applyBindingsToNode(document.getElementById("test"), { template: { name: 'someTemplate', foreach: data } });