看了網上蠻多人都做了自己的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>