如何使用 Backbone 视图在下划线模板中呈现模型属性

How to render model attributes in underscore template using a Backbone view

我在这个问题上花了 2 天时间,但似乎找不到名称值未传递给下划线模板的原因。

我正在从 URL 获取用户,其中 returns 一个值 { "name": "UserName" } (以及更多)我可以在安慰。 然后我获取模型,并使用成功回调将其传递给视图。模板已呈现,但没有值。

在视图中我可以记录属性,但它们不会在下划线模板中呈现。

为什么名称没有在模板中呈现? 没有错误,在视图中我可以记录模型中的属性。

我正在使用 requirejs、backbone 和下划线(以及 jekyll 来创建 html)并且我有以下代码:

主要

require([ 'app' ], function(App){
  App.initialize();
});

应用程序

define(['jquery','underscore','backbone','users/model','users/view'
], function($, _, Backbone, User, ProfileLinkView){
  var initialize = function(){
        console.log("Working")
        user = new User();
        user.fetch({
            success : function(){
                console.log(user)
                var profileLink = new ProfileLinkView({ model : user });
                console.log("pL:", profileLink.el); 
            }
        });
    }
  return {
    initialize: initialize
  };
});

查看

define(['backbone','users/model'], function( Backbone, User ) {

    var ProfileLinkView = Backbone.View.extend({
        el: '#profilelink',
        //template: _.template( "<a href='#'>Len</a>"),
        initialize : function(){
            this.render();

            this.listenTo(this.model, 'change', this.test);
        },
        test : function(){
            alert( "change" );
        },
        render: function() {
            console.log("v", this.model.attributes );
            data = this.model.attributes;
            this.template = _.template( "<a href='#'><%= name %></a>", this.model.toJSON() );
            this.$el.html( this.template( this.template() ) );
            return this;
        },
    })

    return ProfileLinkView
});

型号

define(['underscore','backbone',], function(_, Backbone, User){
    var User = Backbone.Model.extend({
        url: 'http://localhost:3000/users/0',
    })
    return User;
});

结果不正确

<li class="dropdown" id="profilelink"><a href="#"></a></li>

应该是:

<li class="dropdown" id="profilelink"><a href="#">UserName</a></li>

我不确定这部分

this.template = _.template( "<a href='#'><%= name %></a>", this.model.toJSON() );
this.$el.html( this.template( this.template() ) );

你能试试改成这样吗?

this.template = _.template( "<a href='#'><%= name %></a>");
this.$el.html( this.template( this.model.toJSON() ) );

underscore's template的第二个参数是模板设置,不是数据。并且您应该将数据传递到已编译的模板中。