javascript - Handlebars 模板未呈现 - 可以在 Firefox Inspector 中看到 HTML
问题描述
我在外部文件 (user-listing-template.html) 中有一个把手模板,我通过 JQuery Ajax 调用动态加载该文件以检索文件,通过 Handlebars.compile 进行编译,然后在 div 中显示。请参见下面的示例代码:
模板文件:
<script id="user-listing-template" type="text/x-handlebars-template">
<h2 class="ui header">User Maintenance</h2>
<hr>
<h4 class="text-align-left">Total Users: </h4>
<br><br>
</script>
加载模板的JS函数:
function userListroute() {
var source;
var template;
$.ajax({
url: "/templates/user-listing-template.html",
cache: true,
success: function(data) {
console.log('Template Data From File: ' + data);
source = data;
console.log('Template HTML ' + source);
template = Handlebars.compile(source);
console.log('Compiled Template: ' + template);
$('#app').html(template);
}
});
}
在 index.html 中,我有一个 div,我希望在其中看到模板:
<div id="app"></div>
但是,当我运行此应用程序时,不会呈现模板。我可以在 Firefox 开发工具的 Inspector 中看到模板的 HTML 代码:
所有的 console.log() 语句都显示了有效的 HTML 代码,但是它不会显示,我只看到空白页。控制台输出如下所示:
我显然做错了什么,只是不确定是什么——除了渲染位之外,一切似乎都在工作。
非常感谢任何帮助。我对 Handlebars 还很陌生,我只是在尝试一个概念验证应用程序。
解决方案
根据官方网站http://handlebarsjs.com/。您只需编译模板而不生成 html。
template = Handlebars.compile(source);
var html = template(yourdata); // yourdata is the object rendered to your template
$('#app').html(html); // can not be template variable, variable html is final html content
推荐阅读
- php - get_terms WP_Error 对象([错误] => 数组([invalid_taxonomy] => 数组([0] => 无效分类。))[error_data] => 数组())
- android - android谷歌地图标记空指针错误
- php - mysqli查询以更新学生的排名列
- button - python - 如何通过python在bale-messenger中发送带有按钮的消息?
- ios - Apple Pay In App Provisioning - 添加到钱包
- java - 如何为具有重试逻辑的方法编写 junit 测试用例
- c# - 如何在运行时知道属于结构的char数组的长度
- python - 用于在画布上滚动的 Tkinter 鼠标滚轮动作
- javascript - reactjs如何显示结果
- docker - 在 Gitlab 运行器中刷新 Docker 图像缓存