车把编译错误

handlebar compilation errors

本文关键字:错误 编译      更新时间:2023-09-26

嗨,我一直在尝试使用 backbonejs 和车把模板,但似乎我的 jSON 是错误的,或者数据没有正确解析。获得

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

代码可以在以下位置找到

斯菲德尔

任何建议将不胜感激

你的小提琴以各种方式被打破,但很有可能你正在这样做:

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>

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

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

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

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());
    //...
}