Is there any way to render from a html string in knockout?
i.e
var html = ko.renderFromString('<p data-bind="text:name"></p>', {name:"Fred"});
It would be very convenient for what I'm doing.
$(".container").append(html);
$(".container").on("click", "p", function(e){
console.log(ko.dataFor(this));});
If you're reluctant on messing with the Template Engines, try this:
ko.renderFromString = function (html, data)
{
var node = new DOMParser().parseFromString(html, "text/html");
this.applyBindings(data, node.body);
var res = node.body.innerHTML.toString();
this.cleanNode(node);
delete node;
return res;
};
It basically creates a temporary (in-memeory) DOM element from your Html string, binding your data, returning the innerHTML of the bound element then discarding it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With