I am using backbone and i would like to parse my first collection in my view.
My first question, is undescore really the best way to do it? I have heard about mustache.js
The next thing is, i don’t know how to do is:
var A = new Model();
var B = new Model();
var Mole = new Collection([A, B]);
var View = View({model: A, collection: Mole });
View.render();
Here is my render method:
render: function(){
this.template = _.template($('template').html());
$(this.el).html(this.template(this.collection.models)); //I don't know what to send here
}
Here is my template
<script type="text/template" id="template">
<% _.each(collection, function(model){ %> //I don't know what to get here
<% model.name %>
<% }); %>
</script>
First of all,
_.templatewants the text from the template, not a jQuery object. That means that this:should be this:
Then the compiled template function will want to see key/value pairs for the data; from the fine manual (this applies to Mustache, Handlebars, and Underscore BTW):
So you want to say this:
and then you can say this in your template:
A couple points to consider:
this.elinthis.$elso there’s no need to$(this.el).toJSON, this applies doubly so to Mustache and Handlebars since they won’t understand anything else.<%= ... %>to get some output in your template;<% ... %>simply evaluates a bit of JavaScript code, it won’t leave anything behind, you have to use interpolation delimiters (<%=and%>by default) for that.