Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Knockout render html string

Tags:

knockout.js

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));});
like image 785
Chin Avatar asked Mar 11 '26 22:03

Chin


1 Answers

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.

like image 86
haim770 Avatar answered Mar 15 '26 01:03

haim770



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!