1

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?

Gurnard
  • 1,773
  • 22
  • 43

1 Answers1

7

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));
Community
  • 1
  • 1
shash7
  • 1,719
  • 1
  • 18
  • 20