我的Js模版引擎(二)

上次自己尝试着做了下js的模版,发现那种方法解析模版确实太复杂了,这次换了下思路,总体来说,js模版要实现的就是让模版里边的js代码能够运行起来

当然了,还有不少bug,比如支持的分隔标签有限,像{{,{%貌似还不行,ie下也有bug,以后慢慢修复!

以下是模版引擎的核心代码:

/**
 * @author hust_小C
 * email:hustcoolboy@gmail.com
 */

(function(w){
    w.Template=Template||{};
	function Template(options){
	    return this instanceof arguments.callee?this.init(options):new arguments.callee(options);
	}
	Template.prototype={
		init:function(options){
			this.tpl=options.tpl;//待解析的模版
			this.target=options.target||options.tpl;//解析后渲染的模板dom
		    this.tplcontent=options.tpl.text||options.tpl.value;
		    this.left=options.left||"<%";//左分隔符
			this.right=options.rigth||"%>";//右分隔符
			this.body=[];
			this.compiled="";//编译生成的函数
			this.data=options.data;
		},
		parse:function(){
			var self=this;
			this.tplcontent.split(new RegExp('(?='+this.left+')|('+this.right+')')).filter(function(k,v){
                   return !(new RegExp(self.right)).test(v);
            }).each(
			  function(k,v){
			    if((new RegExp('^'+self.left)).test(v)){
				    if(new RegExp('^'+self.left+'\s*=').test(v)){
				       self.body.push(v.replace(new RegExp('^'+self.left+'\s*=(.*)'),'\ttemp.push($1);\n').replace(/\\n/g,''));
				    }else{
					   self.body.push(v.replace(new RegExp('^'+self.left+'\s*(.*)'),'$1\n').replace(/\\n/g,''));
					}
				}//
				else {self.body.push('\ttemp.push(\"'+v.replace(/\n|\t/g,'')+'\");\n');}
			  })
			  return this.body.join("");
		},
		compile:function(){
			if(!this.compiled){
				this.compiled=new Function("json",'var temp=[];\nwith(json){\n'+this.parse()+'}\n return  temp.join("");');
			}
			return this.compiled;
		},
		render:function(){
			this.target.innerHTML=this.compile()(this.data);
		}
	}
})(this);
 Array.prototype.filter=function(fn){
   var temp=[];
   for(var i=0,l=this.length;i<l;i++){
      this[i]&&fn.call(this,i,this[i])&&temp.push(this[i]);
   } 
  return temp;
}
Array.prototype.each=function(fn){
   var temp=[];
   for(var i=0,l=this.length;i<l;i++){
     fn.call(this,i,this[i]);
   } 
   return this;
}
posted @ 2011-04-26 13:00  淘小杰  阅读(467)  评论(2编辑  收藏  举报