Make Your Own Javascript Template Engine

Recently I needed java-script templates to display JSON data coming through a Rest Full Api request.

There are lots of open sourced java-script Template Engines which are really very simple and easy to use like Underscore.js but It was still a lot to read and configure. And the core code will always be woo-do to you, specially in the case when you need to do something out of box.

Would you like to learn to use some library (with spending a day or two ) of js template parsing if I say you can do it in just 20 lines of simple js function and with extreme speed ?

Just give it a try … copy paste below code in one .html file and run
It is lightning fast template parser and the best advantage is its simplicity. You can modify it according to your needs in minutes.

The code is self explanatory and I think I have placed enough comments 🙂

<html>
<head>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
// this is the function who parse the template 
//args
// 1) tId : 'ID of the template div'
// 2) row : json object containing values
function teplateParser(tId,row)
{
    var p = $('#'+tId).html();
    p = p.toString();
    var tempVars = getTemplateVars(p);
    for(a in tempVars)
    {
        var temp = tempVars[a];
        temp = temp.split('.');
        var val = row[temp[0]];
        if(val){
        for(k in temp)
        {   
            if(k==0)
             continue;
            if(val[temp[k]])
            val = val[temp[k]]; 
        }
        p = p.replace('{'+tempVars[a]+'}',val);
       }
    }
    return p.toString();
}
// fetches the variable names from templates used in teplateParser
function getTemplateVars(str) {
  var results = [], re = /{([^}]+)}/g, text;
  while(text = re.exec(str)) {
    results.push(text[1]);
  }
  return results;
}

 // this function is perticularly made to display list of records. One can modify it according to needs
function getParsedHtml(mainTId,data,replaceSlug)
{
    var rows = '';
    var flipflop = true;
    for(a in data)
    {
        if(flipflop) data[a].grey = 'white'; else data[a].grey = 'grey'; // for alternate colors in rows
        rows+=teplateParser(mainTId+'Row',data[a]);
        flipflop = !flipflop;
    }
    var html = $('#'+mainTId).html();
    html = html.toString();
    html = html.replace(replaceSlug,rows);
   return html;
}


function showRecords()
{
  // this variable may be loaded by ajax 
  var Data = [ {name : 'Rupesh Patel' , details : { age : 25 , birthdate : '22 oct 1987' , others : {nickname : 'none'},}},
			   {name : 'Rakesh Patel' , details : { age : 22 , birthdate : '14 Apr 1990',others : {nickname : 'rako'},},},
			   {name : 'Nishith Patel' , details : { age : 23 , birthdate : '25 aug 1991',others : {nickname : 'nishu'},}},
			   {name : 'Rajesh Patel' , details : { age : 30 , birthdate : '26 oct 1982',others : {nickname : 'raju'},}},
				];
	$('#container').html(getParsedHtml('users',Data,'__SLUG__'));
}
</script>
<style>
.row{clear:both;}
.col {float:left;width:150px;}
.template {display:none}
.grey .col{background-color:grey}
.white .col{background-color:white}
</style>
</head>
<body>

	<input type="submit" onclick="showRecords()" value="show" />

	<!-- container div !-->
	<div id="container"></div>


	<!-- main container temlate -->
	<div id="users" class="template">
	<div class="row"> <div class="col header">NAME</div>  <div class="col header">Nick Name</div> <div class="col header">Age </div> <div class="col header">Bitrh Day </div></div>
	__SLUG__ <!-- This slug will be replaced with parsed html of rows -->
	</div>
	<!-- Template of a row must have Id followed by "Row"-->
	<div id="usersRow" class="template"> 
		<div class="row {grey}">
			<div class="col">{name}</div> <div class="col">{details.others.nickname}</div> <div class="col">{details.age}</div> <div class="col">{details.birthdate}</div>
		</div>
	</div>
</body>
</html>

Happy Javascript Template Parsing :),
Rupesh Patel

Advertisement