模板引擎探究一二

  何为模板引擎?从mustache到handlebars、jquery的模板插件jquery.tmpl、以及我厂的etpl~事实上模板引擎的实现原理并不复杂,但是写一个对开发者友好且性能较高的模板引擎并不容易。but,各个模板引擎的性能高低以及好坏不在讨论的范畴(如果你对此有强烈的兴趣,请参看《深入浅出nodeJS》一书的第八章相关的模板部分分析,当然你也可以参看下面的一篇博客,高性能Javascript模板引擎原理分析),理解模板引擎的实现原理,从John Resig的Micro-template入手,相关博客为Javascript Micro-Templating

 

  直接看代码

// Simple JavaScript Templating
// John Resig - http://ejohn.org/ - MIT Licensed
(function(){
  var cache = {};
 
  this.tmpl = function tmpl(str, data){
    // Figure out if we're getting a template, or if we need to
    // load the template - and be sure to cache the result.
    var fn = !/\W/.test(str) ?
      cache[str] = cache[str] ||
        tmpl(document.getElementById(str).innerHTML) :
     
      // Generate a reusable function that will serve as a template
      // generator (and which will be cached).
      new Function("obj",
        "var p=[],print=function(){p.push.apply(p,arguments);};" +
       
        // Introduce the data as local variables using with(){}, 动态执行 javascript 字符串,with改变作用域,访问到data
        "with(obj){p.push('" +
       
        // Convert the template into pure JavaScript
        str
          .replace(/[\r\t\n]/g, " ")
          .split("<%").join("\t")
          .replace(/((^|%>)[^\t]*)'/g, "$1\r")
          .replace(/\t=(.*?)%>/g, "',$1,'")
          .split("\t").join("');")
          .split("%>").join("p.push('")
          .split("\r").join("\\'")
      + "');}return p.join('');");
   
    // Provide some basic currying to the user
    return data ? fn( data ) : fn;
  };

// test
console.log(this.tmpl('<h1><%=text1 %></h1><h2><%=text2 %></h2>', {text1: 'text1 hello', text2: 'text2 hello'}));
})();

  

  

  

posted @ 2014-11-25 11:23  gyy_Jade  阅读(366)  评论(0编辑  收藏  举报