Per un progetto recente ho deciso di provare jQuery invece del collaudatissimo framework prototype.

Una delle cose di cui ho sentito subito la mancanza è un sistema di template semplice come quello integrato con prototype, dopo aver provato alcuni dei plugin di jQuery che sembravano fare al mio caso, ho scritto in una decine di righe un mini sistema di template che mi ha permesso di supplire velocemente a questa mancanza.

/** * 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 “Un semplicissimo sistema di template in JavaScript”

Trackbacks/Pingbacks

  1.  JavaScript Template Library » Pomo T.I