laijbin / Blog

Note insights and personal development.
0 stars 0 forks source link

写一个简单的模板引擎 #6

Open laijbin opened 9 years ago

laijbin commented 9 years ago

关于最好的模板语言?

JavaScript模板引擎原理,几行代码的事儿

JavaScript Micro-Templating

mustache模板

underscore

最简单的JavaScript模板引擎

laijbin commented 8 years ago

实现:

exports.$tmpl = {
      cache : {},
      tmpl : function(str,data,context){
          var fn= !/\s/.test(str) ? 
              this.cache[str]=this.cache[str] || this.tmpl(document.getElementById(str).innerHTML) :
          new Function("obj","/*debugger;*/var p='';p+='"
              +str.replace(/[\r\n\t]/g," ")
              .split('\\').join("\\\\")
                 .split("<%").join("\t")
                 .replace(/((^|%>)[^\t]*)'/g, "$1\r")
                 .replace(/\t=(.*?)%>/g, "'+$1+'")
                 .split("\t").join("';")
                 .split("%>").join("p+='")
                 .split("\r").join("\\'")
              +"';return p;");
          return data? (context?fn.call(data, context):fn.call(data)):fn;
      }
    }