javascript - Handlebars 编译错误

标签 javascript backbone.js handlebars.js

您好,我一直在尝试使用backbonejs和 Handlebars 模板,但似乎我的json错误或数据未正确解析。获取

Uncaught Error: You must pass a string to Handlebars.compile. You passed undefined

代码可以在

找到

jsfiddle

如有任何建议,我们将不胜感激

最佳答案

您的 fiddle 以各种方式损坏,但很可能您正在这样做:

template: Handlebars.compile($('#tpl-page-list-item').html()),

之前有一个#tpl-page-list-item可用的。如果您的页面如下所示,就会发生这种情况:

<script src="your_backbone_javascript.js"></script>
<script id="tpl-page-list-item" ...></script>

因为您的 Backbone View 将在 <script id="tpl-page-list-item"> 之前被解析被添加到 DOM 中。您可以将 Backbone View 包装在文档就绪处理程序中(使用适当的命名空间来说明函数包装器):

$(function() {
    window.PageListItemView = Backbone.View.extend({
        template: Handlebars.compile($('#tpl-page-list-item').html()),
        //...
    });
});

或者在实例化 View 时编译模板:

initialize: function() {
    // Or check if it is in the prototype and put the compiled template
    // in the prototype if you're using the view multiple times...
    this.template = Handlebars.compile($('#tpl-page-list-item').html());
    //...
}

关于javascript - Handlebars 编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19845027/

相关文章:

javascript - 根据用户输入返回值

javascript - 如何使 AngularJS 指令处于事件状态

javascript - 将 require.js 与独特的 CDN 结合使用

javascript - Backbone/Marionette CollectionView - 在模板内渲染?

node.js - 当 GET 路径不存在时,如何自动返回 404?

javascript - 为什么按索引插入节点的方法不起作用?

javascript - 由 JavaScript 和 AJAX 支持的动态网站的 SEO

javascript - 从 Backbone View 下划线模板访问模型属性

php - MySQL bool 类型

webpack - 将 .json 文件从 html-webpack-plugin 传递给 Handlebars 模板