Skip to content

Instantly share code, notes, and snippets.

@developit
Created January 29, 2015 16:22
Show Gist options
  • Save developit/17b1b775aa6c40d01357 to your computer and use it in GitHub Desktop.
Save developit/17b1b775aa6c40d01357 to your computer and use it in GitHub Desktop.
template=function(l){var q={},r={_default:function(b){return this[b.value&&b.value.splice?"each":"if"](b)},each:function(b){var h="",a,f=b.value;for(a in f)f.hasOwnProperty(a)&&(h+=l(b.content,f[a],void 0));return h},"if":function(b){return b.value?l(b.content,b.fields,b.overrides):""},"else":function(b){return b.value?"":l(b.content,b.fields,b.overrides)},unless:function(b){return this["else"](b)}};return l=function(b,h,a){var f=/\{\{\{?([#\/\:]?)([^ \{\}\|]+)(?: ([^\{\}\|]*?))?(?:\|([^\{\}]*?))?\}?\}\}/g,
g="",c,d,e,m,k=[];a={fields:h||{},overrides:a||q};a.path=(a.overrides.__path__?a.overrides.__path__+".":"")+a.overrides.__key__;for(f.lastIndex=0;d=f.exec(b);){0===k.length&&(g+=b.substring(c||0,f.lastIndex-d[0].length));c=d[1];if(!c||"#"!==c&&":"!==c&&"/"!==c){if(c=d[2],0===k.length)if(e=a.overrides[c]||h[c],null==e)g+=d[0];else{c="{"!==d[0].charAt(2);if(d[4])for(m=d[4].split("|"),d=0;d<m.length;d++)if(helpers.hasOwnProperty(m[d])){"html"===m[d]&&(c=!1);var n=m[d].split(":"),p=helpers[n[0]];"string"===
typeof p?e=l(p,e,0):(n.splice(0,1,e),e=p.apply(helpers,n))}c&&(e=String(e).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;"));g+=e}}else{if("/"===c||":"===c)a.id=k.pop(),a.value=a.overrides[a.id]||h[a.id],0===k.length&&(a.content=b.substring(a.blockStart,f.lastIndex-d[0].length),(e=r[a.blockHelper](a))&&"string"===typeof e&&(g+=e)),a.previousBlockHelper=a.blockHelper,a.previousId=a.id,a.previousValue=a.value;if("#"===c||":"===c)d[3]||d.splice(2,0,"_default"),k.push(":"===
c?a.id:d[3]),1===k.length&&(a.blockHelper=d[2],a.blockStart=f.lastIndex)}c=f.lastIndex}return g+=b.substring(c)}}();
document.body.innerHTML = template('\
<h2>Hello, {{name}}!</h2>\
<ol>\
{{#list}}\
<li>{{n}}</li>\
{{/list}}\
</ol>\
', {
name : 'World',
list : [
{n:'a'}, {n:'b'}, {n:'c'}
]
}
);
@developit
Copy link
Author

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