zoukankan      html  css  js  c++  java
  • 我的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;
    }
    
  • 相关阅读:
    python--将jenkins配置的任务导出到Excel
    python--终端工具之subprocess
    jquery-触底加载无限滚动
    python-比较字典value的最大值
    Linux-查看cpu核数和个数、查看内存的命令
    python读取本地正在运行的docker容器
    关于get 和post 方法的比较
    git相关的一篇不错的文章
    Java 函数调用是传值还是传引用? 从字节码角度来看看!
    Unity3D移动平台动态读取外部文件全解析
  • 原文地址:https://www.cnblogs.com/hust/p/2029198.html
Copyright © 2011-2022 走看看