Search code examples
backbone.jsunderscore.js

Variable passing on Backbone template


I just started learning 'Backbone.js', I am currently following this video tutorial. For templating, I just kept my template to be simple like this -

<script type="text/template" id="songlist_template">
<%_.each(songs, function(song){});  %>
<h1>Loaded</h1>
</script>    

and my view extended as-

var SongList=Backbone.View.extend({
el:'.page',
render: function(){
    var that=this;
    var songs=new Songs();
    songs.fetch({
        success:function (){
            var temp=_.template($("#songlist_template").html());
            var html=temp(songs);
            that.$el.html(html);
            },
        error: function (collection, response, options) {
            alert("error!! "+response.responseText); 
            }})
}});

Everything is perfect until I reach templating section where console log says-

Uncaught ReferenceError: songs is not defined is not defined.

According to documentation , I think my template syntax is OK and I have passed the correct fetched data. Furthermore I have also defined variable songs. It would be helpful if someone can point it out my mistake.

Complete code here and json file here.


Solution

  • to fix your issue pass the songs as array temp({songs:songs.models})

    in success callback you could add the parameter songs

      success:function (songs){
                var temp=_.template($("#songlist_template").html());
                var html=temp({songs:songs.models});
                that.$el.html(html);
                },
    

    http://backbonejs.org/#Collection-fetch

    The options hash takes success and error callbacks which will both be passed (collection, response, options) as arguments