问题
I recently inherited this from another developer, and what was left behind for me has me stumped.
I am trying to build a set-up in which the first 3 objects in my JSON array are rendered on the page via mustache, then with a click, the next 3 load, and so forth. Where I'm stuck right now is just figuring out how to make Mustache only render 3 objects. I've done quite a bit of searching but I can't seem to find the syntax.
There is no code associated with the 'load-more' button yet. I figured I'd start with the first part of the puzzle.
Alternatively, is there a better solution than mustache for this kind of layout?
Here is what I have so far:
<div id="bios"></div>
<!-- JSON data -->
<div id="divInsightsData">
<script>
var prof_data = {
bios: [
{ name: "John Smith",
title: "Title 1",
office: "New York"
},
{ name: "John Smith",
title: "Title 2",
office: "New York"
},
{ name: "John Smith",
title: "Title 3",
office: "New York"
},
{ name: "John Smith",
title: "Title 4",
office: "New York"
},
{ name: "John Smith",
title: "Title 5",
office: "New York"
},
{ name: "John Smith",
title: "Title 6",
office: "New York"
}
]};
var template="{{#bios}}<div class='bio'><p class='author-details'>{{name}}</p><p class='author-details'>{{title}}</p><p class='author-details'>{{office}}</p></div>{{/bios}}";
var html = Mustache.render(template, prof_data);
$("#bios").append(html);
</script>
</div>
<a href="#" class="load-more">Load More</a>
回答1:
If only the first 3 elements of the array are what you're presenting, then the entire array is not your view-model and you should not pass it to mustache.
It is possible to pass a function to Mustache for this, but it is not the "Mustache Way"
The less logic you have in your mustache templates, the more debug-able and maintainable they are. This is the strong point of using Mustache for templating. They should accept your view-model as is and work with that, rather than apply logic to it and try to manipulate it.
Let's say you have your
var prof_data = {
bios: [
{ name: "John Smith",
title: "Title 1",
office: "New York"
},
{ name: "John Smith",
title: "Title 2",
office: "New York"
},
{ name: "John Smith",
title: "Title 3",
office: "New York"
},
{ name: "John Smith",
title: "Title 4",
office: "New York"
},
{ name: "John Smith",
title: "Title 5",
office: "New York"
},
{ name: "John Smith",
title: "Title 6",
office: "New York"
}
]};
You can create a:
var prof_data_viewmodel = {
bios: prof_data.bios.slice(0,3)
};
And pass that to Mustache instead
来源:https://stackoverflow.com/questions/16428497/mustache-js-rendering-only-a-limited-number-of-array-objects