Backbone.js Jade and the model cycle

I am a bit confused about templates using trunk with jade / underscore.

I have a basic model with several arrays in it, and I'm not sure how to visualize the attributes of the array. I could move them to a separate collection and view the main chain, but in this case it seems like overkill.

I followed in this blog post about using jade trunk and added the following to my main file

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

which allows me to display the model attributes in this estate:

  //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 make a simple loop over one of the arrays in the model. eg.

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

but I am pretty confused about the correct syntax where jade and underline begins etc. Thanks.

+7
source share
1 answer

You cannot use jade in the browser (well, you probably can technically, but it is not so often used with the base, not the underline). There you will use underline patterns. The documents on the _.template page show that you can evaluate javascript and use the _.each method to loop through the attributes of the model array.

This will look like the one shown in your render function. You want to cache the template function as an attribute of your view for efficiency, but I have it built in here for simplicity. Suppose, 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 evaluate syntax in the settings of your template, as this example includes both the interpolation style ( <%= ) and the evaluation style ( <% ) of the template markup. Currently, you just have a mustache style interpolation, and that’s not enough.

+5
source

All Articles