Reputation: 855
I am working on rendering HTML from mustache template engine.
I am stuck in rendering when it comes to deal with a list of objects.
Here is my object:
var Prod={
"Object1": {
"name": "name1",
"category": "laptop"
},
"Object2": {
"name": "name2",
"category": "laptop"
},
"Object3": {
"name": "name3",
"category": "Desktop"
},
"Object4": {
"name": "name4",
"category": "Mobile"
}
}
Here is what I am trying to render from:
var template='{{#Prod}} {{name}} and {{category}} {{/Prod}}'
Mustache.render(template, {"Prod":Prod});
But it is not working, and I do not understand why.
Please suggest me where I am wrong.
Upvotes: 3
Views: 4416
Reputation: 16779
You need to make your list of products an array for the automatic iteration of lists functionality to kick in. No need to have each product accessible by keys Object1
, Object2
, Object3
, etc.
Edit: If you can't change the object format, you can turn one format into the other fairly easily using Object.keys
and Array#map
:
var Prod={
"Object1": {
"name": "name1",
"category": "laptop"
},
"Object2": {
"name": "name2",
"category": "laptop"
},
"Object3": {
"name": "name3",
"category": "Desktop"
},
"Object4": {
"name": "name4",
"category": "Mobile"
}
}
var products = Object.keys(Prod).map(function (k) { return this[k] }, Prod)
document.body.innerHTML = Mustache.render('\
<ul>\
{{#products}}\
<li>{{name}} and {{category}}</li>\
{{/products}}\
</ul>\
', { products: products })
<script src="https://cdnjs.cloudflare.com/ajax/libs/mustache.js/2.3.0/mustache.min.js"></script>
Upvotes: 3
Reputation: 3683
It looks like Prod
is an object and not a list.
If you change your code to the following, I believe it should work.
var Prod = [
{
"name": "name1",
"category": "laptop"
},
{
"name": "name2",
"category": "laptop"
},
{
"name": "name3",
"category": "Desktop"
},
{
"name": "name4",
"category": "Mobile"
}
}
var template='{{#Prod}} {{name}} and {{category}} {{/Prod}}'
Mustache.render(template, { "Prod":Prod});
Upvotes: 3