tempura
Version:
A light, crispy, and delicious template engine
1 lines • 2.07 kB
JavaScript
!function(e,r){"object"==typeof exports&&"undefined"!=typeof module?r(exports):"function"==typeof define&&define.amd?define(["exports"],r):r(e.tempura={})}(this,(function(e){const r=/(\r?\n)+$/g,i=/^\d|[^A-Za-z0-9_$]/g,t=/{{\s*([\s\S]*?)\s*}}/g;e.compile=function(e){return new Function("xyz",e)},e.transform=function(e,n={}){let s,f,l,a,o,c=!!n.minify,u=n.locals||{},g=[],p={},h=0,$="",m="";function x(){$.length>0?m+=(m?"x+=":"=")+"`"+(c?$.replace(/([\t\s]+(?=<|$)|(\r?\n)+)/g,""):$)+"`;":0===m.length&&(m='="";'),$=""}function d(e){if(p[e]||u[e])return e;let r,t=0,n="",s=e.split(/[.]|(\[['"`]?.*[`'"]?\])/g);for(;t<s.length;t++)(r=s[t])&&(0===t&&(p[r]||u[r])?n+=r:(0===t&&(n+="xyz"),"["===r[0]?n+=r:n+=i.test(r)?`[${JSON.stringify(r)}]`:"."+r));return n}for(;s=t.exec(e);){$+=e.substring(h,s.index).replace(r,""),h=s.index+s[0].length;let i=s[1].trim();if(f=i.charAt(0),"!"===f);else if("#"===f)if(x(),[,a,i]=/^#\s*([a-zA-Z]+)\s*(.*)/.exec(i),"expect"===a)o=i.trim().split(/[\n\r\s\t]*,[\n\r\s\t]*/g),m+=`var{${o.join(",")}}=xyz;`,o.forEach(e=>u[e]=!0);else if("var"===a)l=i.indexOf("="),o=i.substring(0,l++).trim(),i=i.substring(l).trim(),u[o]=!0,m+=`var ${o}=${i.replace(/[;]$/,"")};`;else if("each"===a)if(l=i.indexOf(" as "),~l){o=i.substring(0,l).trim(),i=i.substring(l+4).trim();let[e,r="i"]=i.replace(/[()\s]/g,"").split(",");m+=`for(var ${r}=0,${e},arr=${d(o)};${r}<arr.length;${r}++){${e}=arr[${r}];`,g.push(a+"~"+e+","+r),p[e]=p[r]=!0}else o=i.trim(),m+=`for(var i=0,arr=${d(o)};i<arr.length;i++){`,g.push(a+"~i"),p.i=!0;else if("if"===a)m+=`if(${d(i.trim())}){`,g.push(a);else if("elif"===a)m+=`}else if(${d(i.trim())}){`;else{if("else"!==a)throw new Error("unknown - "+JSON.stringify({action:a}));m+="}else{"}else if("/"===f)if(x(),i=g.pop(),a===i||"else"===a&&"if"===i)m+="}";else{if("each"!==a||!i.startsWith("each~"))throw new Error("mismatch – "+JSON.stringify({expect:i,actual:a}));m+="}",i.substring(5).split(",").forEach(e=>{p[e]=!1})}else $+="${"+d(i)+"}"}return h<e.length?($+=e.substring(h).replace(r,""),x()):x(),"var x"+m+"return x"}}));