Un semplicissimo sistema di template in JavaScript

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

  1. Guido Serra Says:
    25 August 2007 at 14.11  

    che plugin di wordpress hai usato per l’hilighting del codice?

  2. Alessandro Pasotti Says:
    26 August 2007 at 19.03  

    Questo:

    http://wordpress.org/extend/plugins/wp-syntax/

  3. Jure Says:
    30 November 2007 at 20.53  

    Thanks for this code. Saved my day.

  4. JavaScript Template Library » Pomo T.I Says:
    08 September 2008 at 20.01  

    [...] utilizando bibliotecas de template para JavaScript. Eu pessoalmente prefiro a simplicidade do zTemplate, mas também existem projetos mais robustos como o JavaScriptTemplates, PURE, ou o [...]

Lascia un Commento