So I have been working on some web development projects that required me to create multiple html elements with dynamic data pulled from a database. So I did some searching on ways to easily template with jquery.
There are 2 essential parts to this method of templating. First you create the html markup that you wish to repeat. That is placed inside a script tag and will look something like this:
First off we need to place our html template into a variable and initialize a variable called body that we will use to append to the <ul> tag later.
Next we create the array that we are going to use to fill out our list items. This usually is created via an ajax call to the database but for this tutorial we will do it in the function.
Now we are coming to the workhorse of the templating: the $.each() function in jquery. This allows me to loop through my array and use the items inside each row to replace the placeholder data with information from the array.
Now we are ready to take our body variable and append it to <ul> tag with an ID of ‘Tutorial’.
That’s it! Now this is a very simplified version but this format can easily be tweaked to fit all sorts of situations. Below is the code at work as well as the source code: