Skip to content

Instantly share code, notes, and snippets.

@neesenk
Created October 8, 2011 09:57
Show Gist options
  • Save neesenk/1272085 to your computer and use it in GitHub Desktop.
Save neesenk/1272085 to your computer and use it in GitHub Desktop.
js前端的模版
/**
* 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