模板渲染引擎

 1  var template = (function () {
 2             /*  Simple JavaScript Templating
 3              John Resig - http://ejohn.org/ - MIT Licensed */
 4             var cache = {};
 5             return tmpl = function (str, data) {
 6                 /* Figure out if we're getting a template, or if we need to */
 7                 /* load the template - and be sure to cache the result. */
 8                 var fn = !/W/.test(str) ? cache[str] = cache[str] || tmpl(document.getElementById(str).innerHTML) :
 9 
10                     /* Generate a reusable function that will serve as a template */
11                     /*  generator (and which will be cached). */
12                         new Function("obj", "var p=[],print=function(){p.push.apply(p,arguments);};" +
13 
14                                     /* Introduce the data as local variables using with(){} */
15                                 "with(obj){p.push('" +
16 
17                                     /* Convert the template into pure JavaScript */
18                                     /* modified by yiguo .for extension function */
19                                 str.replace(/[
	
]/g, " ").split("<%").join("	").replace(/((^|%>)[^	]*)'/g, "$1
").replace(/	=(.*?)%>/g, function (a, b, c) {
20                                     var arr = b.split("|");
21                                     if (arr.length > 1) {
22                                         b = "tmpl.fns['" + arr[1] + "' ](" + arr[0] + ",'" + arr[2] + "')";
23                                     }
24                                     return "'," + b + ",'";
25 
26                                 }).split("	").join("');").split("%>").join("p.push('").split("
").join("\'") + "');}return p.join('');");
27 
28                 /* Provide some basic currying to the user*/
29                 return data ? fn(data) : fn;
30             };
31         })();
原文地址:https://www.cnblogs.com/hanfei-cn/p/5199083.html