小巧的html模板引擎
小巧的html模板引擎
今天看coco大神的github,看到了他写的html模板引擎,默默地记录下来,其实,模板引擎我自己也写过一个,不过总觉得大神写的一定比我的好,点击这是我写的
先贴出代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
|
(function(name, definition) { if (typeof define === 'function') { define(definition); } else { this[name] = definition(); } })('cotemplate', function() { var tplReg = /\$\{\s*([^\{\}\s]+)\s*\}/g; var jsReg = /(^( )?(if|for|else|switch|case|break|{|}))(.*)?/g;
var code = 'var r=[];\n'; var match = 'undefined'; var pointer = 0;
function lineAdd(line) { code += 'r.push("' + line.replace(/"/g, '\\"') + '");\n'; }
function cotemplate(tpl, data) { while (match = tplReg.exec(tpl)) { lineAdd(tpl.slice(pointer, match.index));
code += ('r.push(String(this.' + match[1] + '));');
pointer = match.index + match[0].length; }
lineAdd(tpl.substr(pointer, tpl.length - pointer));
code += 'return r.join("");';
console.log(code);
return new Function(code.replace(/[\r\t\n]/g, '')).apply(data); }
return cotemplate; });
|
用法Demo
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| <script src="../js/cotemplate.js"></script> <script> var data = { name: 'Coco', info: { age: 18 }, bar: { foo: { else: 'co-template' } } }
var tpl = ` <p>name:${coco}</p> <p>Age:${info.age}</p> <div>${bar.foo.else}</div> `;
cotemplate(tpl, data); // <p>Name:Coco</p> // <p>Age:18</p> // <div>HTML-template:co-template</div> </script>
|