How do you put a template on a page with vanillaJS?
-
When a template is inserted in html, the browser makes a mistake in the console that the transferable parameter is not a DOM knot:
Uncaught TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'
In fact, the question is, how can the template be inserted in the html document on the vanilla violin? I'd like three lines, like it's done on Jquery on the off site handlebars.
var data = { "array": [ { "position": "one", "data": "Тут находятся какие-то данные" }, { "position": "two", "data": "Тут находятся другие данные" }, { "position": "three", "data": "Тут нет данных вообще, кроме этой записи" } ] }
var source = document.getElementById("template").innerHTML;
var template = Handlebars.compile(source);document.body.appendChild((template(data)));
-
As a result of the challenge
template
a line is produced which has been formed by supplying data to the reference template. An example of jQuery works because in http://api.jquery.com/append/ You can give HTML the line - jQuery will dissolve it, create an element and add it to the page. However, https://developer.mozilla.org/en/docs/Web/API/Node/appendChild accepts only the existing element. This can be solved by manually establishing the element.innerHTML
the value of the HTML row and add the element to the page. As with jQuery browser will dissolve it and create the necessary DOM.var html = template(data);
var container = document.createElement('div');
container.innerHTML = html;document.body.appendChild(container);
http://jsbin.com/vuceziculo/edit?html,js,output
Added
In the example above, an additional element will be created that varies the template, which will often be prevented. No additional element used https://developer.mozilla.org/en/docs/Web/API/DocumentFragment ♪ It's a so-called container, which in itself is not a complete element, but which supports many of its functions. When you put him on the page, his contents will be inserted. So he doesn't support
innerHTML
the contents will have to be transferred to it from a real intermediate element:var html = template(data);
var container = document.createElement('div');
container.innerHTML = html;var fragment = document.createDocumentFragment();
// appendChild "вырезает" детей
while (container.childNodes[0]) {
fragment.appendChild(container.childNodes[0]);
}document.body.appendChild(fragment);
http://jsbin.com/dopevinazi/1/edit?html,js,output