2basix automatisering

Websites en custom made software


XTPL Micro templating in JS

This subject/concept is not new. Micro or just templates are around for many years and they are really usefull for generating HTML with javascript using a template and RAW data.

Other nice looking javascripts:

My code is based on an example from John Resig from july 2008. The quickly made example there is quite raw and is not really good for usage, but the idea is quite good.
for this article see: John's article...

I wont go to deep on how this all works, because its quite difficult to explain.
It is easy to use which is far more important.

What I did is I took this idea and I made a complete new templating engine.
This template engine is SO small and fast, that I think its the leanest and maybe the fastest one you will find.

Enough said, here the complete engine..

//   Micro JavaScript Templating   xtpl (minified version)
//   Leo Lems - http://2basix.nl - MIT Licensed
(function(){this.xtpl=function xtpl(templatestring,data){var ret='',xfn=new Function("o","var arr=['"+templatestring.replace(/[\r\t\n]/g,"").split("'").join("\\'").replace(/{%=\s*\(\s*(.+?)\s*\)\s*%}/g,"',($1),'").replace(/{%=\s*(.+?)\s*%}/g,"',(o.$1)?o.$1:'','")+"']; return arr.join('');");if(!data){return xfn}return xfn(data)}})();

Notice that this minified version is smaller then 400 bytes... Yes...
When I was finished with this, it was just perfect, fast and small and no overhead code B)


// the character based template
var Templ="<div id=\"{%=id%}\" class=\"{%= ( i % 2 == 1 ? \"even\" : \"\" ) %}\">{%=text%}</div>";

// some json test data (4 records)
var data2= [ 	{id:"1", text:"John says... Hello you JS devs.. "},
		{id:"2", text:"this is a second line"},
		{id:"3", text:"the third line"},
		{id:"4", text:"The finishing line"}  ];

var html="";	
//==-- HTML generation 
// create a function based on the string template
var RenderFunc = xtpl(thetemplate);

for (i = 0; i < data2.length; i++ ) {
	html += RenderFunc(data2[i]);


The example will produce:

Now this is a very simple example, but you can really make difficult templates which will be rendered fast.

Download the complete html example below if you want to quickly experiment with it..

Have FUN...

Download: XTPL Micro templating in JS

Filesize: 2KB
Downloaded: 112 times

Contact Info

Telefoon: +31 6 20350595

My status