js模版的初步嘗試

來源:互聯網
上載者:User

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.