A super-simple JavaScript templating system
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;
}
}




2007-08-25 at 2.11 pm
che plugin di wordpress hai usato per l’hilighting del codice?
2007-08-26 at 7.03 pm
Questo:
http://wordpress.org/extend/plugins/wp-syntax/
2007-11-30 at 8.53 pm
Thanks for this code. Saved my day.
2008-09-08 at 8.01 pm
[...] 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 [...]