I am having trouble passing a Backbone collection to an Underscore template in my HTML. Right now in the template code <%=teamCollection%> is undefined. teamCollection is the Backbone collection I want to pass from the Backbone view into the template.
Here is the template code:
<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>
And here is the Backbone code:
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);
}
});
here is a JSFiddle that corresponds to this question, which I obviously can't get working either: http://jsfiddle.net/the1mills/26dkh5wa/
teamCollection
is undefined in the template becauseteamCollection
is undefined in the javascript code. I can't find in your code the declaration orteamCollection
.