使用Handlebars和Backbone

50

我正在学习Backbone/Handlebars/Require。我已经在网上和Stack Overflow上搜索了很多 - 你能给我指引一些教程或网站,为使用handlebars而不是underscore提供有用的信息吗?


3
最佳的文档资料来源是 Handlebars 网站,您可以在 http://handlebarsjs.com 找到它。关于如何使用 Handlebars 和 Backbone,没有额外的复杂度或差异。唯一的区别就是您需要包含 Handlebars,但除此之外,它的使用方式与将 Underscore 作为模板引擎相似。希望这能帮到您。 - Bart Jacobs
谢谢你的帮助!我们还需要包括下划线吗,还是可以省略? - Joseph at SwiftOtter
8
是的。下划线是Backbone所依赖的组件,它对下划线有很强的依赖性。 - Bart Jacobs
4个回答

80

使用 handlebars.js 替代 underscore 模板是相当简单的。请查看以下示例:

https://cdnjs.com/libraries/backbone.js/tutorials/what-is-a-view (滚动到“Loading a Template”一节)

SearchView = Backbone.View.extend({
    initialize: function(){
        this.render();
    },
    render: function(){
        // Compile the template using underscore
        var template = _.template( $("#search_template").html(), {} );
        // Load the compiled HTML into the Backbone "el"
        this.el.html( template );
    }
});

在Backbone中,通常的惯例是在一个渲染函数中构建你的HTML。使用模板引擎完全由你自己决定(这也是我喜欢Backbone的原因)。所以你只需要将它改为:

SearchView = Backbone.View.extend({
    initialize: function(){
        this.render();
    },
    render: function(){
        // Compile the template using Handlebars
        var template = Handlebars.compile( $("#search_template").html() );
        // Load the compiled HTML into the Backbone "el"
        this.el.html( template );
    }
});

由于你正在使用 require.js,所以可以将 Handlebars 作为模块的依赖项放在顶部。我对此还比较新,但听起来需要关注的是 Backbone.js 模式和 require.js 的用法。


如果您喜欢将模板保存在单独的文件中,那么如何加载它们呢?我想到了 sammy.js 的方式,您可以在其“render”方法中指定模板文件的地址。 - Kris Selbekk
2
当使用 Backbone.ModelBackbone.Collection 作为模板上下文时,请记得使用 .toJSON() - Matt Stone
如果您已经使用下划线作为模板引擎开发了一个应用程序,那么这并不是那么简单的。下划线允许您在模板中编写JavaScript代码(当然,您必须使用特殊标记),但Handlebars则不行。 - Ravi Hamsa
是的,@RaviHamsa,迁移将是一个不同的挑战,因为模板语言具有不同的功能。如果你想切换,建议你只使用Handlebars编写所有新模板,直到达到临界质量,然后在重构工作中迁移旧内容。 - SimplGy

2

我希望在初始化时只编译一次模板,这样就避免了每次渲染时重新编译模板。此外,你需要将模型传递给已编译的模板,以生成HTML:

SearchView = Backbone.View.extend({
  initialize: function(){
    // Compile the template just once
    this.template = Handlebars.compile($("#search_template").html());
    this.render();
  },
  render: function(){
    // Render the HTML from the template
    this.$el.html(this.template(this.model.toJSON()));
    return this;
  }
});

1

如果您正在使用require.js,您将无法使用当前的Handlebars文件。我使用了以下Handlebars插件,它似乎与当前版本保持更新。如果Handlebars在您的模块中返回null,请使用上述插件替换您的Handlebars文件。


0
define(["app", "handlebars",
    "text!apps/templates/menu.tpl"
], function (app, Handlebars, template) {

    return {
        index: Marionette.ItemView.extend({
            template: Handlebars.compile(template),
            events: {
                'click .admin-menu-ref': 'goToMenuItem'
            },
            goToMenuItem: function (e) {
               //......
            }
        })
    }
});


 new view.index({model: models});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接