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:
This html markup can now be used to dynamically populate a <ul> tag with a little javascript/jquery.
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.
var body = ”;
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.
[‘Analytics’,‘Yes we are a google partner’],
[‘Training’,‘We do training too!’]];
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.
{
body += template.replace( //ig, obj[0] )
.replace( //ig, obj[1] );
});
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:
<html>
<head>
<title>Jquery Templating Source</title>
<script id=‘TemplateTest’ type=‘template’>
<li class=‘item’>
</li>
</script>
<script type=‘text/javascript’ src=‘http://code.jquery.com/jquery-1.6.2.js’></script>
</head>
<body>
<ul id=‘Tutorial’>
</ul>
</body>
<script type=‘text/javascript’>
$(document).ready(function()
{
var template = $.trim( $(‘#TemplateTest’).html() );
var body = ”;
var items = [[‘Infotrust’,’Best Company Ever!’],
[‘Analytics’,’Yes we are a google partner’],
[‘Training’,’We do training too!’]];
$.each( items, function( index, obj )
{
body += template.replace( //ig, obj[0] )
.replace( //ig, obj[1] );
});
$(‘#Tutorial’).append(body);
});
</script>
</html>