Search code examples
backbone.jsunderscore.jsmustache

how to parse a backbone collection in a template view


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>

Solution

  • First of all, _.template wants the text from the template, not a jQuery object. That means that this:

    this.template = _.template($('template'));
    

    should be this:

    this.template = _.template($('template').html());
    

    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):

    When you evaluate a template function, pass in a data object that has properties corresponding to the template's free variables.

    So you want to say this:

    this.$el.html(this.template({
        collection: this.collection.toJSON()
    }));
    

    and then you can say this in your template:

    <% _.each(collection, function(model) { %>
      <%= model.name %>
    <% }); %>
    

    A couple points to consider:

    1. Backbone views already have a jQuery wrapped this.el in this.$el so there's no need to $(this.el).
    2. Serialized data is generally passed to templates using toJSON, this applies doubly so to Mustache and Handlebars since they won't understand anything else.
    3. You need to say <%= ... %> 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.