Reputation: 3000
I need to create multiple divs like below based on how many objects are in my collection
<div class="container">
<a href="#">title test</a>
<div class="video">
video test
</div>
</div>
I want to use jquery to acheive this.
for(i =0 ;i < list.size; i++){
$("#wrapper").append(createDiv(list[i]));
}
function createDiv(object){
return <div class="container">
<a href="object.link">object.title</a>
<div class="video">
object.video
</div>
</div>;
}
I feel this way to too hard coded as I may need to reconstruct the container
class. For example I may want to put in another div tag or more links. I'm wondering if there is an alternative way to do this that would allow flexibility in my code. Instead of createDiv
return one large string, should I be using query functions such as createElement
?
Thanks for any advice :)
Upvotes: 0
Views: 863
Reputation: 18351
The best way to handle this type of problem is with a templating library. Templates allow you to define your HTML markup as strings with tokens in them.
Then you can apply the template to a list of items, and it will replace the tokens with the matching properties from each item. This cleans up your code by eliminating the need to loop through the list.
There are several popular templating libraries:
Here's a quick example of how you might use jQuery templating on a list of items:
var gridTemplate = '<div class="my-item">' +
'<div class="my-list-item-value">${ItemName}</div>' +
'<a href="#">$[DeleteLink]</a>' +
'</div>';
$.templates("gridTemplate", gridTemplate);
Underscore.js allows you to define your HTML in an actual .html
document, which keeps your JavaScript files cleaner. Then you are free to change the HTML template any way you like without affecting your JavaScript as long as you keep the tokens in your HTML file.
Here's a good article about templating with Underscore.js.
Upvotes: 3