Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using loops in backbone/underscore's templates

I have a backbone.js/underscore.js template that I am feeding into a backbone view for rendering. The View is passed a model that contains an array posts of objects (which I call post in the template).

Problem: When I try to loop through all the elements of the array posts, I get an error Uncaught SyntaxError: Unexpected token ) and refers a line in the backbone View's code template: _.template( $('#tpl_SetView').html() ).

Am I doing the loop incorrectly which is causing this error?

Template code

<script type="text/template" id="tpl_SetView">     <div class="row_4">         <div class="photo_container">             <div class="set_cover">                 <img src="/<%= posts[0].thumb_subpath %><%= posts[0].img_filename %>" width=240 />             </div>             <div class="set_thumbs">                 <%= _.each(posts, function(post) { %>                     <img src="<%= post.thumb_subpath %><%= posts.img_filename %>" width=55 />                 <%= }); %>             </div>         </div>     </div> </script> 
like image 998
Nyxynyx Avatar asked Aug 02 '12 15:08

Nyxynyx


1 Answers

To echo a variable use <%= %>, but to parse javaScript code, just use <% %>.

For example:

// In your Backbone View var posts = {"posts": this.model.toJSON()}; var template = _.template($("#tpl_SetView").html(), posts);   // In your template <div class="row_4">     <div class="photo_container">         <div class="set_cover">             <img src="/<%= _.escape(posts[0].thumb_subpath) %><%= _.escape(posts[0].img_filename) %>" width=240 />         </div>     <div class="set_thumbs">         <% _.each(posts, function(post){ %>             <img src="<%= _.escape(post.thumb_subpath) %><%= _.escape(posts.img_filename) %>" width=55 />         <% }); %>         </div>     </div> </div> 
like image 151
James Woodruff Avatar answered Sep 18 '22 21:09

James Woodruff