if(typeof Text == "undefined"){ var Text = {} } Text.QuickTemplate = function(){ this.initialize.apply(this, arguments); return this; }; // static function Text.QuickTemplate.extend({ clear_cache : function(){ Text.QuickTemplate.prototype.cache = {}; return this; } }); Text.QuickTemplate.prototype = { initialize : function(){ this.params = {}; this.tmpl = this.get(arguments[0]) || arguments[0]; this.delimiters = ["\\{\\{", "\\}\\}"]; if(arguments[1]) this.extend(arguments[1]); var str = this.delimiters[0]+"(.*?)"+this.delimiters[1]; this.sep = new RegExp(str,"g"); }, cache : {}, clear_cache : function(){ Text.QuickTemplate.prototype.cache = {}; return this; }, param : function(){ var self = this; arguments.toArray().forEach(function(v,i){ self.params.extend(v) }); return this; }, clear : function(){ this.params = {}; return this; }, get : function(id){ var self = this; if(self.cache[id]){ return self.cache[id] } var d = document.getElementById("tmpl_"+id); if(!d){return null} var tmp = d.innerHTML; self.cache[id] = tmp.replace(/(\r|\n|\t)*?(\r|\n|\t)*/g,""); return self.cache[id] }, set : function(id,value){ var self = this; self.cache[id] = value; return this; }, compile : function(){ var str = ""+this.delimiters[0]+"(.*?)"+this.delimiters[1]+""; var sep = new RegExp(str,"g"); var buf = []; var builder = function(){ var param = arguments.callee.param; arguments.toArray().forEach(function(v,i){ param.extend(v) }); return buf.join("") }; builder.param = {}; var last = 0; this.tmpl.replace(sep,function(){ var a = arguments; buf.push(a[3].slice(last,a[2])); last = a[2] + a[0].length; var n = []; n.toString = function(){ return builder.param[a[1]] ? builder.param[a[1]].toString ? builder.param[a[1]].toString() :"" :"" } buf.push(n); return arguments[1]; }); buf.push(this.tmpl.slice(last)); return builder; }, fill : function(){ var self = this; var buf = this.tmpl; var arg = arguments; var sep = this.sep; arg.toArray().forEach(function(v,i){ self.params.extend(v) }); return buf.replace(sep,function(){ return (undefined == self.params[arguments[1]])?"":self.params[arguments[1]]; }); }, fill_expr : function(){ var self = this; var buf = this.tmpl; var arg = arguments; var sep = this.sep; arg.toArray().forEach(function(v,i){ self.params.extend(v) }); return buf.replace(sep,function(){ var match = arguments[1]; var pair = match.split("="); if(pair.length == 2){ self.params[pair[0]] = pair[1]; return ""; } var p = self.params[arguments[1]]; if(typeof p == "function"){ return p.call(self.params) } return (undefined == p)?"":p; }); }, toString : function(){ return this.fill(); } }; var QT = Text.QuickTemplate; String.prototype.fill = function(){ var tmp = new QT(this); return tmp.fill.apply(tmp,arguments); }; String.prototype.fill_expr = function(){ var tmp = new QT(this); return tmp.fill_expr.apply(tmp,arguments); };