Skip to content

Instantly share code, notes, and snippets.

@v1vendi
Last active June 28, 2016 21:53
Show Gist options
  • Select an option

  • Save v1vendi/a9410a0c5d40901d8541288701f1ce72 to your computer and use it in GitHub Desktop.

Select an option

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)
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, '&lt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#39;')
.replace(/`/g, '&#96;');
}
return fragment;
}
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,'&amp;')[m](/>/g,'&gt;')[m](/</g,'&lt;')[m](/"/g,'&quot;')[m](/'/g,'&#39;')[m](/`/g,'&#96;'),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+"`}")}
@v1vendi
Copy link
Author

v1vendi commented Jun 28, 2016

Actually minified version returns not DocumentFragment, but pure compiled text

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment