Moving from prototype framework to jQuery, I missed the nice templating engine that was available as a prototype plugin. After some testing with the templating plugins for jQuery, I wrote this few lines to have a super-simple templating system readily available.

/** * Simple template system * Usage: * var t = new Template('
'); * var html = t.run({id : 'div_one', class : 'my_class'}); */ Template = function(tpl){ this.tpl = tpl; this.tokens = []; this.is_compiled = false; this.compile = function(){ var re = /\{(\w+)\}/g; var tok; while((tok = re.exec(this.tpl)) != null) { this.tokens.push(tok[1]); } this.is_compiled = true; } this.run = function(json){ if(!this.is_compiled){ this.compile(); } if(json){ for (var jk = 0; jk < this.tokens.length; jk++){ var pattern = new RegExp('\{' + this.tokens[jk] + '\}', 'g'); this.tpl = this.tpl.replace(pattern, json[this.tokens[jk]]); } } return this.tpl; } }

4 Responses to “A super-simple JavaScript templating system”

Trackbacks/Pingbacks

  1.  JavaScript Template Library » Pomo T.I