js模版的初步尝试

看了网上蛮多人都做了自己的js模版引擎,自己也看了很长一段时间源码,今天突然也想试下怎么写模版引擎,于是就琢磨了一下午,初步完成了if(包括else)标签

的解析,希望路过的高手多多指教!

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
		

	</head>
	<body>
		<script>
			/**
 * @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.tags=["if"];//存放模版标签,目前制作了if的解析,日后在进行扩展
	Template.prototype={
		init:function(o){
			this.tpl=o.tpl;//待解析的模版
			this.target=o.target||o.tpl;//解析后渲染的模板dom
		    this.tplcontent=o.tpl.innerHTML.replace(/\n|\t/g,'');
		    this.left=o.left||"{{";//左分隔符
			this.right=o.rigth||"}}";//右分隔符
			this.vars=[];
			this.body=[];
		},
		parseif:function (){
			var tplcontent=this.tplcontent.split(new RegExp('(?='+this.left+'if)'));
			var temp=[];
			for(var i=0,len=tplcontent.length;i<len;i++){
				temp.push(tplcontent[i].replace(new RegExp(this.right+'(.*?)'+this.left,'g'),function(){
					 return "{this.vars.push('"+arguments[1]+"')}";
		            }
		           ).replace(new RegExp(this.left+'\s*(.*)\/if\s*'+this.right),'$1'));
			}
			return temp.join('');
		},
		compile:function(){
			var self=this;
			this.tplcontent.replace(new RegExp(Template.tags.join('|')),function(){
				self.body.push(self['parse'+arguments[0]]());
			})
		    return new Function(this.body.join('')+"   return this.vars.join('')").call(this);
		},
		render:function(){
			this.target.innerHTML=this.compile();
		}
	}
	
})(this);

		</script>
	<div id="tpl">
		{{if(a==2)}}
		<h1>小C</h1>
		{{else}}
		<h1>hust_小C</h1>
		{{/if}}
		
		
		{{if(b==2)}}
		<h1>小C</h1>
		{{else}}
		<h1>hust_小C</h1>
		{{/if}}
		
		{{if(c==2)}}
		<h1>小Cwqeqwerqwr</h1>
		{{else}}
		<h1>hust_小C11111111111111111</h1>
		{{/if}}
		
		{{if(d==2)}}
		<h1>第四个if语句</h1>
		<h1>hust_小C2324124125125</h1>
		{{/if}}
		
		
	</div>
	解析后的文本
	<div id="tpltext">
	</div>	
	<script>
		var a=2,b=1,c=4,d=2;
		var tpl=Template({tpl:document.getElementById('tpl'),target:document.getElementById('tpltext')});
		tpl.render()
	</script>
	</body>
</html>
posted @ 2011-04-23 16:46  淘小杰  阅读(386)  评论(0编辑  收藏  举报