Created
October 8, 2011 09:57
-
-
Save neesenk/1272085 to your computer and use it in GitHub Desktop.
js前端的模版
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* js前端的模版 | |
* zhiyongliu <zhiyongliu@tencent.com> | |
* | |
* 支持两种指令: <!-- -->, <!--{}--> | |
* 1. <!-- --> js的控制结构的代码;不包含输出 | |
* 2. <!--{}--> 输出的内容, 结果为string或可转换为string的表达式 | |
*/ | |
var MyTemplate = MyTemplate || function(id) { | |
var analyze = function (str) { | |
var o = [], p = '__out__.push', m, | |
s = str.replace(/\r|\n/g, "").split('<!--'); | |
for (var i = 0; i < s.length; i++) { | |
m = s[i].split('-->'); | |
if (m.length > 1) | |
o.push(m[0].replace(/^\{([\s\S]+)\}$/, p + "($1);")); | |
if (m[m.length - 1].length > 0) | |
o.push(p + '("' + m[m.length - 1].replace(/("|\\)/g, "\\$1") + '");'); | |
} | |
return o.join(''); | |
}; | |
var tpl = typeof(id) == 'object' ? id : document.getElementById(id); | |
var fcode = "var __out__ = [];" + analyze(typeof(tpl) == 'object' ? tpl.innerHTML:id) + "return __out__.join('');"; | |
return { | |
'render': function (mapping) { | |
var a = [], v = []; | |
for (var i in mapping) | |
a.push(i), v.push(mapping[i]); | |
return (new Function(a, fcode)).apply(null, v); | |
}, | |
'getCode': function () { return fcode; } | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment