Jquery knockout: Render template in-memory

╄→гoц情女王★ 提交于 2019-12-04 05:41:13

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!

f_martinez's answer is really close to what I needed, I just had to specify the template engine to make it 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;
};
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!