无法在模板中显示模型信息

Can't show a model info in template

我想在模板中显示我的模型,但我遇到了问题:

Uncaught ReferenceError: title is not defined

这是我的代码:

    var NewsView2 = Backbone.View.extend({

    NewsView: _.template(NewsView),

    initialize: function () {
                    console.log(this);
        this.$el.html(this.NewsView());
        this.render();
    },
    render: function () {

        this.$el.html(this.NewsView());
        var html = this.NewsView(this.model.toJSON());
        this.$el.append(html);
        return this;
    }

});

初始化:

            var news2 = new News({
            author: "costam",
        });
        var widok2 = new NewsView2({model: news2});

我模板中的代码:

<html>
<head>
</head>
<body>
        <%= title %>
</body>

有人可以帮我吗?我不知道该怎么做。

您的模型没有标题属性。 UnderScore 模板正在抱怨,因为它试图在您的新闻模型中查找不存在的标题 属性。

您的 Backbone 观点:

var NewsView2 = Backbone.View.extend({

    initialize: function () {            
        this.render();
    },

    render: function () {            
        var template = _.template($("#yourTemplate").html())            
        var html = template(this.model.toJSON());
        this.$el.append(html);
        return this;
    }
});

您的模特:

var news2 = new News({ author: "costam", title : "Your title" });

模板:

<html>
<head>
</head>
<body>
   <script type="text/template" id="yourTemplate">
     <%= author %> // --> this should match/exist in your model 
     <%= title %> // --> this should match/exist in your model 
   </script>
</body>

注意:设置 backbone 模板的方法有多种,例如 this