JQuery knockout: visualize a template in memory
I have a knockout pattern:
<script id="draggableHelper" type="text/x-jquery-tmpl"> <div class="draggableHelper"> <span data-bind="text: Name"></span> </div> </script> Is it possible to create a template result and save it in memory by sending an object to fill out a template?
Sort of:
var result = ko.renderTemplate($("#draggableHelper").html(), { Name: "Test" }); +6
2 answers
Yes, it is possible to apply bindings to nodes that are not bound to the DOM. Just use the very useful ko.applyBindingsToNode function 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:
It was originally a ko.renderTemplate method, but there is a built-in method in Knockout with the same name. Overriding ko.renderTemplate may stop working with your application, especially if you use the template binding. Be careful!
+14
Answer to
f_martinez is really close to what I need, I just had to specify a template engine for it to work. My function:
var renderTemplate = function (name, data) { // create temporary container for rendered html var temp = $("<div>"); // apply "template" binding to div with specified data var options = { template: { name: name, data: data, templateEngine: new ko.nativeTemplateEngine() } }; ko.applyBindingsToNode(temp[0], options); // save inner html of temporary div var html = temp.html(); // cleanup temporary node and return the result temp.remove(); return html; }; 0