核心提示:Object.defineProperties(HTMLElement.prototype, {innerString: {get: function () {var map = {: , : , :...
Object.defineProperties(HTMLElement.prototype, { innerString: { get: function () { var map = {"&": "&", "<": "<", ">": ">", "'": "'", """: '"'}; return this.innerHTML.replace(new RegExp(Object.keys(map).join("|"), "g"), function (str) { return map[str]; }); } }, compile: { value: function (sc, data, has_clone) {//([template],[data]) try { typeof sc === "string" || (has_clone = data, data = sc, sc = this._tmpl || this.innerString); typeof sc === "string" && (this._tmpl = new Function("$param", "has_clone"/*"has_clone=" + has_clone*/, "var $this=(has_clone!==undefined?has_clone:" + has_clone + ")?this.cloneNode():this;" + "var r=[];with(typeof $param!=='undefined'?$param:($param={})){" + sc.replace(/|[\r\t\n]/g, " ") .replace(/(^|%>)(?!<%)(.+?)(?=$|<%)/g, function (res, p1, p2) { return p1 + "r.push('" + p2.replace(/'/g, "\\'") + "');"; //"$1r.push('$2');" }) .replace(/<%=(.+?)%>/g, "r.push($1);") .replace(/<%|%>/g, "") + //""<% %>内需要以;结束的每个语句后必须带; "};" + "$this.innerHTML=r.join('');return $this;" ).bind(this)); return data !== undefined ? this._tmpl(data,has_clone) : this._tmpl; } catch (e) { console.error(e); return false; } } } });
顺便给dom补全了个innerString属性,用于获取html转义前的dom内容,compile([sc, ][data,] [has_clone])为模板引擎的主方法;
sc[String]、data[Object]、has_clone[Boolean]三个为非必传参数:
1. sc可以为外部模板字符串(如果没有就使用模板dom的innerString);
2. data为构造数据(如果不传该参数则返回模板的构造方法,存在该参数则返回构造后的dom,模板内可使用key或者$param.key(当不确定某个key是否存在时使用$param.key方法引用较稳)引用data里的某个键);
3. has_clone可在首次编译时指示默认编译结果是否为克隆dom,后面如果需要重新构造也可传该参数代表当前编译结果是否为克隆dom
(功能略多不好描述,上面这些可以掠过看下面的例子)
seover="this.compile([2, 3]);"><%forEach(function(i){%> <%=i+1%> <%});%>
模板格式只需要注意,可执行部分放<% %>内,插入内容放<%= %>内,即可,可支持任何js语法