未在模板中显示模型默认值

时间:2014-04-13 18:43:35

标签: javascript backbone.js underscore.js handlebars.js

我有以下骨干应用程序:

在index.html上:

<div class='content'></div>

<div class='container'>
   <script type="type="text/x-handlebars-template"" id="product-template">
       <h2>Products</h2>

       <h3>{{ this.title }}</h3>
   </script>
</div>

和main.js:

$(function() {

var Product = Backbone.Model.extend({
    defaults: {
        title: "Title",
        user_id: 0,
        description: "Description"
    }
});

var ProductView = Backbone.View.extend({
    el: ".content",
    initialize: function() {
        this.render();
    },
    render: function() {
        var source = $('#product-template').html();
        var template = Handlebars.compile(source);
        var html = template(Product.model);
        this.$el.html(html);
    }
});

var productView = new ProductView();

});

它展示了&#34;产品&#34;标题,因此模板正在渲染,但它没有显示{{this.title }}。不幸的是,控制台中也没有出现任何错误。

1 个答案:

答案 0 :(得分:1)

试试这个:

var ProductView = Backbone.View.extend({
    el: ".content",
    model: new Product,
    initialize: function() {
        this.render();
    },
    render: function() {
        var source = $('#product-template').html();
        var template = Handlebars.compile(source);
        var html = template(this.model.toJSON());
        this.$el.html(html);
    }
});

打印

{{ title }}