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

Underscore templates with Backbone


I'm completely new in backbone framework. I have a model itemsOnSaleModel that contains an array of items and a View itemListView that render these items. The problem is that I can't figure out how to write the template correctly. Usually in this case I would have written something like this:

<script type="text/template" id="listTemplate">

        <ul id = "list">
            <% for (var i=0; i< items.length; i++) { %>
            <li><%=items[i].age %><br>
            <%=items[i].name%><br>
            <%=items[i].id%><br>
            <img src="<%=items[i].imageUrl%>"/><br>
            <%=items[i].snippet%><br>
           <p>Price: <%=items[i].price%></p>
                <button id="<%=items[i].id%>" class="buyButton btn btn-success" type="submit">Buy</button>
            </li>
            <% } %>

    </ul>
</script>

Code example:

var itemsOnSaleModel = Backbone.Model.extend({
    defaults:{
        _items: null
    }
});

var itemListView = Backbone.View.extend({
    _template: _.template($('#listTemplate').html()),
    el: $('#phonesDiv'),
    events: {
    'click .buyButton':'_addToCart'
    },
    initialize: function () {
        'use strict';

        this.render();
    },
    render: function () {
        'use strict';
        var rendTemplate = this._template(this.model.attributes);
        this.$el.html(rendTemplate);
        return this;
    }
});
    var itemsOnSale = new itemsOnSaleModel;
     itemsOnSale.set({'_items': phones});
    var itemList = new itemListView({model: itemsOnSale});

Example of phones array that is being passed to the model:

var phones = [
    {
        "age": 0,
        "id": "motorola-xoom-with-wi-fi",
        "imageUrl": "img/phones/motorola-xoom-with-wi-fi.0.jpg",
        "name": "Motorola XOOM\u2122 with Wi-Fi",
        "snippet": "The Next, Next Generation\r\n\r\nExperience the future with Motorola XOOM with Wi-Fi, the world's first tablet powered by Android 3.0 (Honeycomb).",
        "price": 150
    },

Solution

  • Your problem is that you are referencing a collection items in your template but you aren't passing that in to your template. You can either change the template to use _item instead (<% for (var i=0; i< _items.length; i++) { %> ...) or alternatively when you compile your template you can pass in your item list to the items variable in your template for example

    var rendTemplate = this._template({items: this.model.get('_items')});