10行代码实现一个JS模板引擎

326 阅读1分钟
//核心代码
let template = {
	escape:{
          "'":"\\'",
          "\\n":"\\\\n",
          "\\r":"\\\\r",
          "\\":"\\\\"
     	}
      	,reg:/'|\\n|\\r|\\/g
}
template.compile = function(tpl){
    tpl = tpl.replace(/[\s\t\r\n]+/g," ")
    .replace(/\{\{#\s*([\s\S]+?)\s*\}\}/g,"');$1__a.push('")
    .replace(/\{\{\s*([\s\S]+?)\s*\}\}/g,"');__a.push($1);__a.push('")
    tpl = "var __a = [];__a.push('"+tpl+"');return __a.join('')";
    tpl = tpl.replace(/__a.push\('([\S\s]+?)'\)/g,function(){
                let arg = arguments;
                return template.reg.test(arg[1]) ? arg[0].replace(arg[1],arg[1].replace(template.reg,(arg)=>template.escape[arg])) : arg[0]
            })
    let compileFn = new Function("d",tpl);
    return function(data){
        return compileFn.call(this,data)
    }
};

使用方法

<div id="app"></div>
<script type="text/html" id="tpl">
    {{# if(d.type == 2){ }}
        {{# for(var i = 0; i < 3; i++){  }} 
            <div>dfdf</div>
            <div>水电费</div>
            <div>{{d.name}}</div>
            <div>{{ d.name ? "aa" : "jj" }}</div>
        {{# } }}
    {{# }else{ }} 
        <div>sdf</div>
    {{# } }}
</script>
let tpl = document.getElementById('tpl').innerHTML
,render =  template.compile(tpl);
document.getElementById('app').innerHTML = render({name:'ck',type:2});