自己根据前些天热门的模版引擎文章,弄了一个模版引擎
<!doctype html> <html> <head> <meta charset="utf-8"> <title>template_by_mySelf</title> </head> <body> <script> var str = ''; var data = ['1','2','3','4']; var time = '16:05'; var age = 26; var tpl = "aaa_bbb{%time%};cccc;{%var str='';for(var i=0; i<data.length; i++){str+=data[i];}%};{%str%}dddd;{%(1)%}eeeee{%console.log('console')%}{%end%}"; var reg = /{%([^%]+)?%}/g; var str = "var a = [];"; var mat; var arr = []; var cursor = 0; arr.push(str); while( 1 ){ mat = reg.exec(tpl); if( mat[1] == "end" ){ break; }; arr.push( '\''+tpl.substr(cursor, mat.index-cursor)+'\''); arr.push( mat[1] ); cursor = mat[0].length+mat.index; }; arr.push( tpl.substr(cursor) ); arr.pop(); var result = ''; for(var i=0; i<arr.length; i++){ var frag = eval( arr[i] ); result += frag == undefined ? '' : frag; }; console.log( result ); </script> </body> </html>
重新修改, 使用底线库的写法:
<html> <head> <style> </style> </head> <body> </body> <script id="tpl" type="text/plain"> i的值是: <%var i=4%> wolegequ <%i%>; 内容是: <%for(var i=0;i<4;i++){%> i的值是<%i%> <%}%> <%text%> end </script> <script> var el = document.getElementById("tpl"); var data = { arr : [1,2,3,4], text : "myText" }; var render = function(string , data) { //要把字符串内部的{{}}语句解析到数组中, 把无关的字符串直接push到数组中; var arr = []; var str = string.replace(/\n/g,"\\n"); //使用非贪婪匹配,匹配所有{{}}标签 var reg = /<%[\w\W]+?%>/g; var regOut = /(^( )?(var|if|for|else|switch|case|break|{|}))(.*)?/g; var res = null; var index = 0; while(res = reg.exec(str)) { //把所有非{{}}的内容直接push到arr中; arr.push('array.push("'+str.substring(index, res.index)+'");'); index = res.index + res[0].length; //否则把{{ }}中的内容直接放到数组中; var state = res[0].replace(/<%([\w\W]+)%>/,"$1"); //如果是JS语句到话 if(state.match(regOut)) { arr.push(state+";"); }else{ //如果JS变量的话,直接把变量放到里面来; arr.push("array.push("+state+");") } }; arr.push('array.push("'+str.substring(index)+'");'); console.log(arr.join("")); var fn = new Function("arg", "\ with(arg){ \ var array=[]; "+arr.join("")+"; \ return array.join(\"\");\ };"); return fn(data); }; // var fn = function() { // with(data){ // return(console.log(arr)); // } // } document.body.innerHTML = render(el.innerHTML, data); </script> </html>
天道酬勤