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 🙂

<script src=""></script>
// this is the function who parse the template 
// 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]];
        for(k in temp)
            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)) {
  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
        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'},}},
.col {float:left;width:150px;}
.template {display:none}
.grey .col{background-color:grey}
.white .col{background-color:white}

	<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 -->
	<!-- 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>

Happy Javascript Template Parsing :),
Rupesh Patel


One comment on “Make Your Own Javascript Template Engine

  1. It could include some code to join partials, like header, footer and content in one single html file.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s