Jquery knockout: Render template in-memory
jquery, knockout-2.0, knockout.js
Solution
Yes it's possible to apply bindings to nodes unattached to the DOM. Just use very useful function `ko.applyBindingsToNode` to achieve the desired result.
ko.renderTemplateX = function(name, data){
// create temporary container for rendered html
var temp = $("<div>");
// apply "template" binding to div with specified data
ko.applyBindingsToNode(temp[0], { template: { name: name, data: data } });
// save inner html of temporary div
var html = temp.html();
// cleanup temporary node and return the result
temp.remove();
return html;
};
Take a look at this small example: http://jsfiddle.net/6s4gq/
Update:
Originally it was ko.renderTemplate method but there is built-in method in Knockout with the same name. Overriding `ko.renderTemplate` could stop working your application, especially if you're using `template` binding. Be careful!
Problem
I have a knockout template: ``` <script id="draggableHelper" type="text/x-jquery-tmpl"> <div class="draggableHelper"> <span data-bind="text: Name"></span> </div> </script> ``` Is possible to generate the result of the template, and save it into memory, by sending the object to populate the template? Something like: ``` var result = ko.renderTemplate($("#draggableHelper").html(), { Name: "Test" }); ```