Reputation: 1551
Hi I am currently learning Backbone and have become a little stuck.
Basically I am reading the contents of the below JSON file and rendering to an Underscore template.I am able to send the parameters to my template and have them rendered, with the following code:
var template = _.template( movieView, movInfo);
this.$el.html( template );
And an extract from my template (not the full template):
<section>
<p><%= movie_symptonis %></p>
</section>
And an example of the JSON:
[{
"id": "0",
"name": "Some movie",
"date": "2013",
"time" : "83 MIN",
"rating" : "CERT/ U",
"status" : "AVAILABLE NOW",
"symptonis" : "blah blah blah",
"galleryImages" : {
"image" : "one.png",
"image" : "two.png",
"image" : "three.png"
}
}]
I now need to render some html for each image within the gallery images, I am familar with underscores for each method (_.each). However I am unsure how all this would work together, any help or a push in the right direction would be great.
Thanks in advance
Upvotes: 0
Views: 228
Reputation: 460
You can use the _.each method right inside the template. It will look something like the following.
<section>
<p><%= movie_symptonis %></p>
<% _.each(galleryImages, function(galleryImage){ %>
<img src="<%= this[galleryImage] %>" />
<% }) %>
</section>
"galleryImages" variable is available from the json you are passing to the template.
<% %> delimiter will execute the code like normal javascript.
You can use all constructs available in javascript within the template
(e.g.)
<div>
<% if(condition) { %>
... success html ...
<% } else { %>
... failure html ..
<% } %>
</div>
You can explore more on using constructs in the template. But it is not a good idea to induce too much logic in the template. But it helps to place simple view logic.
Hope that helps you.
Upvotes: 2