Gurnard
Gurnard

Reputation: 1775

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?

Upvotes: 1

Views: 1586

Answers (1)

shash7
shash7

Reputation: 1738

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));

Upvotes: 8

Related Questions