【发布时间】:2016-10-22 08:04:19
【问题描述】:
我正在编写一个使用 handlebars.js 的应用程序,但 The example code on their website 使用 JQuery 以及许多其他在线资源。但是,我想使用 vanilla 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));
但我想使用 vanilla 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'.
如何让它工作?
【问题讨论】:
标签: javascript templates handlebars.js