Last active
January 29, 2016 15:07
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
(function () { | |
// escape function | |
var escape = function (s) { | |
return (s || '').toString() | |
.replace(/&/g, '&') | |
.replace(/</g, '<') | |
.replace(/>/g, '>') | |
.replace(/"/g, '"') | |
.replace(/'/g, '''); | |
}; | |
var base_source = 'var __output="",__escape=' + escape.toString() + ';'; | |
// internal cache | |
var cache = {}; | |
// compiler | |
var template = function (source, data) { | |
// when argument[0] is DOM object, read content | |
if (source.innerHTML) { | |
source = source.innerHTML; | |
} | |
// or, stringify source | |
else { | |
source = source.toString(); | |
} | |
// replace | |
// check cache | |
var ck = source; | |
if (!cache[ck]) { | |
// try to parse css selector | |
try { | |
source = document.querySelector(source).innerHTML; | |
} catch (e) { | |
} | |
// compile | |
// if template source contains syntax error, this line throws exception | |
cache[ck] = new Function('data', base_source + source | |
// constant string | |
.replace(/(^|%>)([\s\S]*?)(<%|$)/g, function (m, a, b, c) { | |
return a + (b && b.length ? ('__output+="' + b.replace(/"/g, '\\"').replace(/(?:\r\n|\r|\n)/g, '\\n') + '";') : '') + c; | |
}) | |
// <%= variable %>; escape print variables | |
.replace(/<%=[\s\n\r]*([\s\S]*?)[\s\n\r]*%>/g, 'try{__output+=__escape($1);}catch(e){}') | |
// <%- variable %>; non-escape print variables | |
.replace(/<%-[\s\n\r]*([\s\S]*?)[\s\n\r]*%>/g, 'try{__output+=($1);}catch(e){}') | |
// <% statement %>; raw javascript stamement | |
.replace(/<%([\s\S]*?)%>/g, '$1;') | |
// return | |
+ 'return __output;'); | |
} | |
// finish; return compiled function or rendered result | |
return data ? cache[ck](data) : cache[ck]; | |
}; | |
// export | |
window.template = template; | |
})(); | |
//(function(){var h=function(s){return(s||'').toString().replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>').replace(/"/g,'"').replace(/'/g,''')};var i='var __output="",__escape='+h.toString()+';';var j={};var k=function(d,f){if(d.innerHTML){d=d.innerHTML}else{d=d.toString()}var g=d;if(!j[g]){try{d=document.querySelector(d).innerHTML}catch(e){}j[g]=new Function('data',i+d.replace(/(^|%>)([\s\S]*?)(<%|$)/g,function(m,a,b,c){return a+(b&&b.length?('__output+="'+b.replace(/"/g,'\\"').replace(/(?:\r\n|\r|\n)/g,'\\n')+'";'):'')+c}).replace(/<%=[\s\n\r]*([\s\S]*?)[\s\n\r]*%>/g,'try{__output+=__escape($1);}catch(e){}').replace(/<%-[\s\n\r]*([\s\S]*?)[\s\n\r]*%>/g,'try{__output+=($1);}catch(e){}').replace(/<%([\s\S]*?)%>/g,'$1;')+'return __output;')}return f?j[g](f):j[g]};window.template=k})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment