使用主干视图为模板添加下划线

Underscore templates with Backbone view

本文关键字:添加 下划线 视图      更新时间:2023-09-26

我在将主干集合传递给 HTML 中的下划线模板时遇到问题。现在在模板代码中<%=teamCollection%>是未定义的。teamCollection 是我想从 Backbone 视图传递到模板中的主干集合。

下面是模板代码:

<script id="user-home-main-table-template" type="text/template">
    <table class="table">
    <thead>
    <tr>
        <th>#</th>
        <th>Team Name</th>
        <th>Club</th>
        <th>Sport</th>
        <th>Delete?</th>
    </tr>
    </thead>
    <tbody>
    <%
    <!--console.log(<%=teamCollection%>);
    var teams = <%=teamCollection%>;
    console.log(teams);-->
    for(var i=0; i
    <teams.length
            ; i++) { %>
       <!-- <tr onclick=window.document.location='/users/<%=user._id%>/teams/<%= teams[i]._id%>/teamDashboard'>-->
        <tr>
            <td>
                <%=i+1%>
            </td>
            <td >
                <a class="font-big" href='/users/<%=user._id%>/teams/<%= teams[i]._id%>/teamDashboard'>
                    <%= teams[i].teamName %>
                </a>
            </td>
            <td>
                <a class="font-big" href='/users/<%=user._id%>/teams/<%= teams[i]._id%>/teamDashboard'>
                    <%= teams[i].club %>
                </a>
            </td>
            <td>
                <a class="font-big" href='/users/<%=user._id%>/teams/<%= teams[i]._id%>/teamDashboard'>
                    <%= teams[i].sport %>
                </a>
            </td>
            <td>
                <a class="btn btn-warning" onclick=window.userHomeMainTableView.deleteTeam('<%=teams[i]._id%>');>delete</a>
            </td>
        </tr>
        <% } %>
    </tbody>
</table>
</script>

这是骨干代码:

var Team = Backbone.Model.extend({
    idAttribute: "_id",
    urlRoot: '/api/teams'
});
var TeamCollection = Backbone.Collection.extend({
    model: Team 
});
var teamCollection = new TeamCollection([]);
var UserHomeMainTableView = Backbone.View.extend({
    tagName: "div",
    collection: teamCollection,
    events: {},
    initialize: function () {
       this.render();
    },
    render: function() {
        //this.template = _.template($('#tmpl').html());
        var userHomeMainTableTemplate = document.getElementById('user-home-main-table-template').innerHTML;
        var template = _.template(userHomeMainTableTemplate);
        //this.$el.html(_.template(userHomeMainTableTemplate)());
        this.$el.html(template({teamCollection:teamCollection}));
        console.log('userHomeMainTableTemplate rendered');
        return this;
    },
    addTeam: function (teamData) {
        console.log('adding team:', team_id);
    }
});

这是一个与这个问题相对应的 JSFiddle,我显然也无法开始工作:http://jsfiddle.net/the1mills/26dkh5wa/

teamCollection

模板中未定义,因为teamCollection在javascript代码中未定义。我在您的代码中找不到声明或teamCollection.