简体   繁体   中英

Handlebars/templating use template as an object

I am looking at using Handlbars templating for my project. Can handlebars return a DOM object or can it only return HTML. For instance if I want to append a child to a DIV can I call DIV.appendChild(myTemplate); Something like this:

var parentDiv = document.getElementById("parentDiv");
for(var i = 0;i<myData.length;i++){
    var source   = $("#my-template").html();
    var template = Handlebars.compile(source);
    var values = myData[i];
    parentDiv.appendChild(template(values));
}

From this I get an arg 1 of appendChild is not an object error thrown, because the rendered template is html/string.

Is there something I can call in handlebars to gerenate objects?

Am I trying to stetch templating too far or is there another solution that behaves in this manner or am I stuck writing createElement manually?

I believe you are looking for this

Use the element.insertAdjecentHTML method to append html string and the dom should convert it into a set of nodes. So you can write something like this :

parentDiv.insertAdjacentHTML('beforeend', template(values));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM