Given a JSON response from my server as follows:
{
"products" : [
{
"Product" : {
"id" : "122",
"name" : "product X",
"price" : "19.99",
},
"Picture" : [
{
"product_id" : "122",
"id" : "145",
},
{
"product_id" : "122",
"id" : "146",
},
{
"product_id" : "122",
"id" : "147",
}
]
}
]
}
I will create a backbone model that will be passed to a backbone View. In my View’s template I can access the product’s name with:
<%= Product.name %>
and all works as expected. But lets say I want to get the id of the first Picture. I tried:
<%= Picture.0.id %>
But I get the following error in my console:
Uncaught SyntaxError: Unexpected number
So in a nutshell how do I access the properties of the various pictures associated with my product from the product template. I am using underscore templates if that matters.
The normal javascript array indexer syntax
[index]will do the trick:Edit: Underscore accepts any old javascript inside the
<% %>tags, so if you want to check whether an array is empty, you can do so using the standard_.isEmptymethod:Or any other javascript construct you prefer. See docs for more info.