Search code examples
backbone.jsunderscore.jsunderscore.js-templating

backbone and underscore template rendering


I'm trying to use backbone to show on a page the result from an API call, I would like to iterate over the collection and create one entry for every element of the collection within my html. It seems I'm missing something cause I see the template tag rendered but none of my items are there. What's the problem with my code?

here the html

<div class="form-group" id="main">
 <% _.each(collection, function(car) { %>
  <div class="form-group">
    <input class="form-control" /><%= car.get("model") %>
  </div>
 <% }); %>
</div>

and here js

var CarView = Backbone.View.extend({
    el: "#main",
    template: _.template($("#main").html()),
    initialize: function() {
        this.render();
    },
    render: function() {
        $(this.el).html(this.template({collection: [{id:1, model:"ford"}, {id:2,model:"kia"}]}));
        return this;
    }
});

var carView = new CarView();

here the fiddle: https://jsfiddle.net/e5hg6rzp/3/


Solution

  • First of all I suggest you to keep your template in <script type='text'/template> ... </script> tag. Secondly you are using .get() method inside your template on plain objects which are do not have this method. In your example you can access property through a . -

     <div class="form-group">
        <input class="form-control" /><%= car.model %>
      </div>
    

    Check this fiddle

    If you want to use Backbone.Collection when you should create Car Collection and Car Model:

    var data = [{
        id: 1,
        model: "ford"
    }, {
        id: 2,
        model: "kia"
    }];
    
    var CarView = Backbone.View.extend({
        el: "#main",
        template: _.template($("#templ").html()),
        initialize: function() {
            this.render();
        },
        render: function() {
            return this.$el.html(this.template(new CarCollection(data)))
        }
    });
    
    var CarModel = Backbone.Model.extend({
        defaults: {
            id: '',
            model: ''
        }
    })
    
    var CarCollection = Backbone.Collection.extend({
        model: CarModel
    })
    
    var carView = new CarView();
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.3.3/backbone.js"></script>
    
    <div class="container">
      <div class="form-inline panel panel-default">
        <div class="form-group" id="main">
    
        </div>
      </div>
    </div>
    
    <script type='text/template' id='templ'>
      <% _.each(models, function(car) { %>
        <div class="form-group">
          <input class="form-control" />
          <%= car.get('model') %>
        </div>
        <% }); %>
    </script>