- /**
- * Author By Cyrus
- * Contact xiaodpro@gmail.com
- * Sample:
- * <code>
- * var template = '<table>'
- * + '<tr><td>${this.firstCellText}-<?echo(this.firstCellText);?></td>'
- * + '<?'
- * + ' var arr = [1, 2, 3, 4, 5, 6];'
- * + ' for(var i = 0; i < arr.length; i++){'
- * + '?>'
- * + ' <td>${arr[i]}</td>'
- * + '<?'
- * + ' }'
- * + '?>'
- * + '</tr>'
- * + '</trable>';
- * console.log(marker(template, {firstCellText: 'The first cell content.'}));
- * </code>
- */
- function marker(v, m){
- function esc(s){return "echo(\\"" + s.replace(/"/g, '\\\\"').replace(/\\n/g, '\\\\n').replace(/\\r/g, '\\\\r') + "\\");"; };
- var o = ["var echo=(function(){var a=new Array();return function(s){if(!s)return a.join('');a.push(s);};})();"],
- s = v.split(/(<\\?|\\?>)/), r = /\\$\\{[^\\}]+\\}/g;
- for(var i = 0; i < s.length; i++){
- var n = s[i];
- if(n === "?>") continue;
- if(n === "<?") o.push(s[++i]);
- else{
- if(r.test(n)){
- var nm = n.match(r), ns = n.split(r);
- o.push(esc(ns[0]));
- for(var j = 0; j < nm.length; j++){
- o.push("echo(" + nm[j].replace(/(\\$\\{|\\})/g, "") + ");");
- o.push(esc(ns[j+1]));
- }
- continue;
- }
- o.push(esc(n));
- }
- }
- var C = new Function(o.join('') + ";this._R$=echo;");
- for(var n in m||{}) if(n != "_R$") C.prototype[n] = m[n];
- return new C()._R$();
- }
- //该片段来自于http://www.codesnippet.cn/detail/0704201512118.html
来源: http://www.codesnippet.cn/detail/0704201512118.html