Augusto Numbers
Augusto Numbers

Reputation: 81

Looping an array in a model with Backbone and handlebars

I'm developing an app with backbone and handlebars for the Bus timetable of my city. The model of one stop is :

    define(["jquery", "underscore", "backbone"],
      function ($, _, Backbone){

    var stop = Backbone.Model.extend({
        defaults : {
            id : "23",
            lon : "43,465187",
            lat : "-80,522372",
            listabus : ["80", "83", "106"]

        }

    });

    return stop;

});

Where "Listabus" is the list of all the bus that pass near the stop number 23. I don't know how I can loop the array in the template...help me! :D thanks in advice

Upvotes: 1

Views: 604

Answers (2)

Vitalii Del Vorobioff
Vitalii Del Vorobioff

Reputation: 525

This is your html:

<!-- below is your template !-->
<script id="bus-stops" type="text/x-handlebars-template">
<ul>
    {{#each stops}}
    <li>{{this}}</li>
    {{/each}}
</ul>
</script>

<!-- result container !-->
<div id="result"></div>

And js code

   var BusStop = Backbone.Model.extend(),
       busStop = new BusStop({stops: ['a', 'b', 'c']});
       template = $('#bus-stops').html(),
       compiler = Handlebars.compile(template),
       html = compiler({stops: busStop.get('stops')});

   $('#result').html(html);

Sorry jsfiddle won't work with handlebars

Upvotes: 2

jmk2142
jmk2142

Reputation: 8581

You just need to pass in your model attributes as an object into the underscore template function. The first argument is the template, the second - your data. You can pass in any object data but underscore plays real nice with model.toJSON() for obvious reasons.

this.$('#insertWherever').html(_.template($('#busList'), stopModel.toJSON()));

And your template would look something like this.

<script id="busList" type="text/html">
<ul>

  <% _.each(listabus, function(busNumber){ %>

    <li><%= busNumber %></li>

  <% }); %>

</ul>
</script>

To summarize, the <% %> is a way to escape and run arbitrary JS code. The <%= %> is a way to interpolate or output stuff into your template.

See http://underscorejs.org/#template and http://underscorejs.org/#each

If you're using require.js, you can download a plugin called text!

This allows you to define HTML files in your dependencies and have your templates reside in their own individual files. This is opposed to the above method which uses an embedded script tag and jquery to grab the template from within whatever view you're working with.

See plugins / text @ http://requirejs.org/docs/download.html

Upvotes: 1

Related Questions