Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone.js Jade and looping over model

I am getting a little confused about templating using backbone with jade/underscore.

I have a backbone model with a couple of arrays in it and am not sure how to render the array attributes. I could move them into a separate backbone collection & view but that seem like overkill in this case.

I followed this blog post on using backbone with jade and added the following to my backbone file

   _.templateSettings = {
      interpolate : /\{\{(.+?)\}\}/g
   };

which allows me to render the model attributes in this manor :

      //in my JavaScript
      this.template = _.template($("#some-template").html());

      //in my .jade template
      input.text(type='text', name="name", value='{{name}}')

what I want to work out is how to do a simple loop over one of the arrays in the model. e.g.

    - for (var child in children)
        {{child}}

but im quite confused about the correct syntax, where jade starts and underscore takes over etc. Thank you.

like image 280
henry.oswald Avatar asked Jul 30 '11 14:07

henry.oswald


1 Answers

You can't use jade in the browser (Well you probably technically can but it's not that common to use with backbone as opposed to underscore). You'll be using underscore templates there. The docs on _.template show that you can evaluate javascript and use the _.each method to loop over your model's array attributes.

It'll end up looking like this inside your view's render function. You'll want to cache the template function as an attribute of your view for efficiency, but I have it inline here for simplicity. Assume for example you have a Car model with a list of drivers as an array of driver names.

var template = "<% _.each(model.drivers, function(name) { %> <li><%= name %></li> <% }); %>";
return _.template(template, this);

Note that you will need to provide an evaluate syntax in your template settings as this example includes both the interpolate style (<%=) and the evaluate style (<%) of template markup. Currently you just have mustache style interpolation and that isn't sufficient.

like image 191
Peter Lyons Avatar answered Oct 29 '22 23:10

Peter Lyons