Wednesday, September 14, 2011

Micro Template - jQuery plugin

Templates

- Accepts an input and renders an output, reusable, cacheable, customizable etc...

There are lots of Browser side (JavaScript) templates are available in the net. All of them provide varied functionalities and features, however they stick to the core 'given an input, provide an output' - mostly HTML.

Few that you should know about are EJS (Embedded JavaScript), Pure, Mustache, JavaScriptTemplate, JQuery Template and more...
All the above and more templates help you create a template in JSP/PHP/ASP like format and accepts a JSON input, mashes them together to return/render a HTML output.

What you have to do?

  1. Download the files
  2. Keep it in your local/server directory.
  3. Refer them in your web page.
  4. Create templates
  5. Create/get JSON object.
  6. Identify the means to mash the template & JSON to get the HTML output.


Each of the above templates has their own API to mash. And they provide simple to heavy features to use.


Micro Templates


As the name says its micro version of templates and does the minimaly required functionality - mashing Template & JSON to create a HTML.

I landed on John Resig's blog about his Micro Template; ~20 lines readable code without comments and does the mashing job wonderfully.
As the code is real short and sweet, it could be included in your own JS (MIT licensed) file and throw away the worry about maintaining additional file(s).

I have modified his code
  1. so that it could be used as jQuery plugin.
  2. to use it within a JSP page, without any hassle. Uses '<#[=]#>' syntax.

Please find below the code and its usage.

Customized Code:


$.fn.mTmpl = function(){ 
 
// Simple JavaScript Templating
// John Resig - http://ejohn.org/ - MIT Licensed
 
var cache = {}
 
   ,tmpl = function (str, data){
 
      // Figure out if we're getting a template, or if we need to
      // load the template - and be sure to cache the result.
      // Veda :- altered the tags to support Templating in JSP
 
      var fn = !/\W/.test(str)
        ? cache[str] = cache[str] || tmpl(document.getElementById(str).innerHTML)
 
        // Generate a reusable function that will serve as a template
        : new Function("obj",
 
          "var p=[],print=function(){p.push.apply(p,arguments);};" +
 
           // Introduce the data as local variables using with(){}
           "with(obj){p.push('" +
 
           // Convert the template into pure JavaScript
           str
              .replace(/[\r\t\n]/g, " ")
              .split("<#").join("\t")
              .replace(/((^|#>)[^\t]*)'/g, "$1\r")
              .replace(/\t=(.*?)#>/g, "',$1,'")
              .split("\t").join("');")
              .split("#>").join("p.push('")
              .split("\r").join("\\'")
           + "');}return p.join('');");
 
        return data ? fn( data ) : fn;
    };
 
    return function(str, data){
       var type = typeof str; 
 
       return (type == 'string')
              ? tmpl(str, data) 
              : (type == 'object')
                ? tmpl($(this).html(), str)
                : tmpl($(this).attr('id'));//if(type == 'undefined') create a template for this.id 
     };//return;
}();//auto initialize the function


How to use:

Go over the HTML and JS tabs below to understand the code. I have enriched the code with comments.