Why We Use jQuery LoadTemplate

Posted By : Rahul Singh | 06-Sep-2017
 
 
 
 
 

Hi, guys, JQuery.loadTemplate is the most beautiful feature in JQuery which provide load HTML file as templates and also pass the JSON object as the template. It is a good feature
to load data in a good manner.

 

It basically displays data as a template which is more readable formats for better user experience. It is more powerful with the simple syntax which supports HTML tag. We load the data in the template and render it on the selected <div> tag by its Id.

 

 
Example 1:

 
<script id="templateList" type="text/x-jquery-tmpl">
<table id="itemList" border="1">
<th width="20%">Name</th>
<th width="20%">Address</th>
<th width="20%">Designation</th>
<th width="20%">Age</th>
<th width="20%">Salary</th>
<tr id="" class="">
<td>${name}</td>
<td>${address}</td>
<td>${designation}</td>
<td>${age}</td>
<td>${salary}</td>
</tr>
{{/each}}
</script>
{{each}} //is used for iterate template data
 
 
<script>
 
var empData = {"data":[{"name":"Rakesh Kumar", "address":"Old delhi", "designation":"Clerk", "age":"25", "salary": "50000"},
{"name":"Shivam Gupta", "address":"New delhi", "designation":"Manager", "age":"45", "salary": "40000"},
{"name":"Ajit Sharma", "address":"Dwarka", "designation":"Accountant", "age":"32", "salary": "56000"},
{"name":"Mohan Singh", "address":"Faridabad", "designation":"clerk", "age":"25", "salary": "20000"},
{"name":"Dinesh Verma", "address":"noida", "designation":"P.O", "age":"42", "salary": "40000"},
{"name":"Karan Jha", "address":"Gurugaon", "designation":"Dpty. Manager", "age":"55", "salary": "50000"},
 
 
 
]}
 
$document.ready(function(){
$JQ("#templateList").tmpl(empData).appendTo( "#templateListView" ); //set template data with the particular view (in
});
</script>
<div id ="templateListView" ></div>
Another example template is below:
 
<script type="text/html" id="template">
<div data-content="employee"></div>
<div data-content="date"></div>
<img data-src="employeePics" data-alt="employee"/>
<div data-content="post"></div>
</script>
 
And to use this do the following:
 
$("#template-container").loadTemplate($("#template"),
{
employee: 'Rahul Singh',
date: '5th Aug 2017',
employeePics: 'employeePics.jpg',
post: 'This is the contents of my post'
});
 
 
Similarly the content of the template can be pass through the html file:
 
$("#template-container").loadTemplate("Templates/template.html",
{
  employee: 'Rahul Singh',
date: '5th Aug 2017',
employeePics: 'employeePics.jpg',
post: 'This is the contents of my post'
});
 
 

About Author

Author Image
Rahul Singh

Rahul singh is a Java Developer and having experience in developing Applications. He is a quick learner.

Request for Proposal

Name is required

Comment is required

Sending message..