我正在写一个使用handlebars.js的应用程序,但The example code on their website使用JQuery,以及许多其他在线资源。不过,我想简单地使用vanilla js编译和渲染一个句柄模板。编译和渲染与香草的车把模板JS
这是HTML模板
<script id="entry-template" type="text/x-handlebars-template">
<div class="entry">
<h1>{{title}}</h1>
<div class="body">
{{body}}
</div>
</div>
</script>
的JS我对编译如下,如回答表明这里 Does Handlebars require jQuery
var source = document.getElementById('entry-template').innerHTML;
var template = Handlebars.compile(source);
了类似的问题。假设我的JSON存储在一个名为myData的变量中。
当谈到渲染与jQuery的模板,你可以简单地做
$('#data-section').append(template(myData));
但我想用香草JS所以我这样做:
var compiledHTML = template(myData);
var dataContainer = document.getElementById('data-section');
dataContainer.appendChild(compiledHTML);
,但我得到的错误
Uncaught TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'.
如何获得此功能?
完美的作品。这是否工作,因为在幕后发生了一些类型转换? – rjbultitude
@rjbultitude有点像https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML – Joseph