<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body>
//模板语法 <script type="text/template" id="underscore"> <ul> <% arr.forEach(function(value,index){%> <li><%=value%></li> <%})%> </ul> </script> <script>
//引擎函数 function template(templateString) { templateString = templateString.replace(/\n/g,"\\n"); var _p=""; var source = ""; var rules = { value:/<%=([\s\S]+?)%>/, express:/<%([\s\S]+?)%>/ }; var regexp = new RegExp(rules.value.source +'|'+ rules.express.source,'g'); var index = 0; templateString.replace(regexp,function (match,value,express,offset) { source += "_p+='"+templateString.slice(index,offset)+"';"; index = offset + match.length; if(value){ source += "_p+="+value+";"; }else if(express){ source+= express+"\n"; } }); source += "_p+='"+templateString.slice(index,templateString.length)+"';\n"; source = "var _p='';\nwith(data){\n "+source +";\n}\nreturn _p"; var _render = new Function( 'data', source ); return function (data) { return _render(data) } } var render = template(document.getElementById("underscore").innerHTML); console.log(render({arr:[11,22,33]})); </script> </body> </html>