Last active
June 28, 2016 21:53
-
-
Save v1vendi/a9410a0c5d40901d8541288701f1ce72 to your computer and use it in GitHub Desktop.
A tiny js template engine using Template Strings and template tag (manually minified is 432 bytes long without gzip)
This file contains hidden or 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 compileTemplate(templateElement, data){ | |
| //hack to get unencoded symbols from HTML node | |
| var textarea = document.createElement('textarea'); | |
| textarea.innerHTML = templateElement.innerHTML; | |
| var text = eval("with(data){html`" + textarea.value + "`}"); | |
| var tmpElement = document.createElement('div'); | |
| tmpElement.innerHTML = text; | |
| var fragment = document.createDocumentFragment(); | |
| while (tmpElement.childNodes.length > 0) { | |
| fragment.appendChild(tmpElement.childNodes[0]); | |
| } | |
| function html(literals, ...substs) { | |
| return literals.raw.reduce((acc, lit, i) => { | |
| let subst = substs[i-1]; | |
| if (Array.isArray(subst)) { | |
| subst = subst.join(''); | |
| } | |
| if (acc.endsWith('$')) { | |
| subst = htmlEscape(subst); | |
| acc = acc.slice(0, -1); | |
| } | |
| return acc + subst + lit; | |
| }); | |
| } | |
| function htmlEscape(str) { | |
| return str.replace(/&/g, '&') // first! | |
| .replace(/>/g, '>') | |
| .replace(/</g, '<') | |
| .replace(/"/g, '"') | |
| .replace(/'/g, ''') | |
| .replace(/`/g, '`'); | |
| } | |
| return fragment; | |
| } |
This file contains hidden or 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
| compileTemplate=(t,d)=>{var b=document,r,m='replace',u='innerHTML',n='childNodes',l='createElement',a=b[l]('textarea'),e=b[l]('div'), | |
| z=a=>a[m](/&/g,'&')[m](/>/g,'>')[m](/</g,'<')[m](/"/g,'"')[m](/'/g,''')[m](/`/g,'`'),p=(l,...s)=>l.raw.reduce((q,w,i)=>{r=s[i-1] | |
| if(Array.isArray(r))r=r.join('') | |
| if(q.endsWith('$')){r=z(r) | |
| q=q.slice(0,-1)}return q+r+w}) | |
| a[u]=t[u] | |
| return eval("with(d){p`"+a.value+"`}")} |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Actually minified version returns not DocumentFragment, but pure compiled text