I am trying to render an array of arrays of objects with a mustache template in javascript, and I have not found anyone else who has asked this question. I can render an array of objects just fine, but I can't figure out how to render an array of them. I could assign each nested array to its own variable I suppose, but there could be any number of them, so I really need to keep them as an array.
Here is the type of data I need to render:
[
[
{ id: 12345, name: "Billy" },
{ id: 23456, name: "Joe" },
{ id: 34567, name: "Jenny" }
],
[
{ id: 45678, name: "Amy" },
{ id: 56789, name: "Julie" },
{ id: 67890, name: "Sam" }
]
]
The outer array could contain any number of nested arrays, and each nested array could contain any number objects.
I don't know if it's possible with mustache. I tried using a function, and this is the first time I've ever used a function with mustache, so maybe I'm doing something wrong. I am calling it from the render function of a Backbone View. The array of arrays (shown above) is part of the view's model's attributes. So here is what I tried.
render:
function ()
{
this.model.attributes.getList =
function ()
{
return function (str, func) { return 'What in the world should I return here?'; }
}
this.$el.html (Mustache.render ($ ('#detail-template').html (), this.model.attributes));
return this;
},
And here is the section of my template where I am attempting to use the function.
{{#getList}}
{{name}}
{{/getList}}
I am pretty sure {{name}} doesn't belong in there, but I have no idea what else I would put in there.
I tried returning func (str), but all it printed was a long string that contained [object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
I could not use that string as a json object, it was just a string.
I'm somewhat new to both backbone and mustache, so I thought someone might have a "best practice" solution to this, or at least could tell me if it is impossible so I don't waste any more time on it. I could not find a similar question anywhere on the Internet.
This question is 2 years old but I guess better late than never. You can use {{.}} to reference the current element in an array.
context = [
[
{ id: 12345, name: "Billy" },
{ id: 23456, name: "Joe" },
{ id: 34567, name: "Jenny" }
],
[
{ id: 45678, name: "Amy" },
{ id: 56789, name: "Julie" },
{ id: 67890, name: "Sam" }
]
]
template = "
{{#context}}
{{#.}}
<span id={{id}}>{{name}}</span>
{{/.}}
{{/context}}
"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With