Project Avant Facebook Page Project Avant Twitter Page

tutorial #5: client-side templating

Client-Side Templating is significantly easier and a more convenient option for updating and changing content. Here, we will use an online cart to demonstrate client-side templating.

In this demonstration, you will learn how to create and use a client-side templating. You will learn how to build the jQuery code needed and the purpose of each line. Also, you will learn about the elements needed to create client-side templating in HTML and CSS.

Below is the demonstration of Client-side templating. You can see within the HTML and CSS structure that the content is being generated by Ajax.

Name Qty. Total

The How-To

HTML

                 

<table id="in-cart">
<thead>

<tr>
<th>Name</th>
<th>Qty.</th>
<th>Total</th>
</tr>
</thead>
<tr class="template" style="display:none;">
<td><span class="item_name">Name</span></td>
<td><span class="item_qty">Quantity</span></td>
<td><span class="item_total">Total</span>.00</td>
</tr>

</table>
                 

CSS


#in-cart  {
	border-collapse: collapse;
    height: auto;
    width: 100%;
}
    

jQuery

                
function template(row, cart) {
//Creates a function that will find variables. 
  row.find('.item_name').text(cart.name);
//Finds the "item_name" attribute inside the table row.
  row.find('.item_qty').text(cart.qty);
//Finds the "item_qty" attribute inside the table row.
  row.find('.item_total').text(cart.total);
//Finds the "item_total" attribute inside the table row.
  return row;//All of the rows will return.
}//Close the function.

$(document).ready(function() {//The functions will be executed, once the page is ready.
  var newRow = $('#in-cart .template').clone().removeClass('template');//Select the "template" attribute, and copies it.
  
   var cartItem = {//Creates a variable called "cartItem".
    name: 'PlayStation 4 Destiny Bundle',//This is a string
    qty: 1,//This is an intger
    total: 449//This is an intger
	
	
  };
  template(newRow, cartItem)//Inserts the data in the table.
    .appendTo('#in-cart')//Adds "in-cart". 
    .fadeIn();//Make the table fade in. 
});//Close