zoukankan      html  css  js  c++  java
  • 模板引擎探究一二

      何为模板引擎?从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(/[
    	
    ]/g, " ")
              .split("<%").join("	")
              .replace(/((^|%>)[^	]*)'/g, "$1
    ")
              .replace(/	=(.*?)%>/g, "',$1,'")
              .split("	").join("');")
              .split("%>").join("p.push('")
              .split("
    ").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'}));
    })();

      

      

      

  • 相关阅读:
    三路快排
    双路快排
    随机快排
    快速排序
    双向链表
    单向链表
    堆排序
    二分插入、bisect
    jmockit使用总结-MockUp重点介绍
    java拼接字符串、格式化字符串方式
  • 原文地址:https://www.cnblogs.com/Iwillknow/p/3948188.html
Copyright © 2011-2022 走看看