ES6 模板编译

顾名思义,就是用反引号编写一个模板字符串,

用echo将模板转为javascrip表达式字符串,

用正则将基础字符串转为想要字符串

将代码封装在函数中返回;

注:

用到es6属性${}

var template=`

    <ul>

    <%for(var i=0;i<data.supplies.length;i++){%>

        <li><%=data.supplies[i]%> </li>

    <%}%>

</ul>`;

function compile(template){

     var  reg1=/<%=(.+?)%>/g;

     var reg2=/<%([sS]+?)%>/g;

     template=template

      .replace(reg1,'`); echo($1); echo(`')

      .replace(reg2,'`);  $1 echo(`');

      template='echo(`'+template+'`)';

     var script=`

           (function parse(data){

               var outpput='';

               function echo(html){

                     output+=html

               }

            ${template}

            return output;

          )}`

      return script

}

var parse=eval(compile(template));

div.innerHTML=parse({supplies:['1',,'2','3']});