Reputation: 3081
I have a situation where I have a load of JSON I need to process, and for each "data" item, output this on the page as a list item. This is fine, however I am conscious of the proper way to do this.
For example, one way which I can only think of is:
$.each(json.data, function(key, value) {
$('ul').prepend("<li><div class='name'>" + value.name + "</div>...<li>");
});
Now this works, however if I have multiple layers of divs and other elements it's just going to get messy. I could make it look better in the code by multi-lining it, but that's still a horrible way to maintain it.
How do I get around this and do/present it properly?
Prehaps a template in another file which I load in, then assign HTML/text to specific elements?
Upvotes: 0
Views: 1515
Reputation: 11353
Basically build a template so you reduce how often you are actually appending to the dom. You can write the same code snipper like this and you can expect it to preform better. Just concat the string locally and inject it all at once.
var html = "", value;
for(var i = json.data.length - 1; i >=0; i--) {//same as prepending (or reverse the list)
value = json.data[i];
html += "<li><div class='name'>" + value.name + "</div>...<li>";
}
$('ul').prepend(html);
Rereading your snippet I can't tell if json.data
is an object or an array. For an object your original method was fine:
$.each(json.data, function(key, value) {
html += "<li><div class='name'>" + value.name + "</div>...<li>";
});
Most templating frameworks provide a nice, minimal way to do build the same html string. If you have a question about doing this in a particular framework, shoot.
Upvotes: 2
Reputation: 29941
You might want to take a look at Mustache.js or Handlebars.js to make client side templates. A small example using handlebars:
<!-- Because of the 'type' attribute, the browser won't try to execute
this as it were javascript -->
<script type="text/x-handlebars-template" id="result-template">
<ul>
{{#each results}}
<li>
<div class='name'>{{name}}</div>
<div class='age'>{{age}}</div>
</li>
{{/each}}
</ul>
</script>
For rendering:
var source = $("#result-template").html();
var template = Handlebars.compile(source);
// The 'template' function returns the rendered HTML
var ul = $(template({results: jsonData}));
ul.appendTo("body");
Working example: http://jsbin.com/ESIKiDoK/1/edit
Upvotes: 1