easytemplate.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. var easyTemplate = function(s,d){
  2. if(!s){return '';}
  3. if(s!==easyTemplate.template){
  4. easyTemplate.template = s;
  5. easyTemplate.aStatement = easyTemplate.parsing(easyTemplate.separate(s));
  6. }
  7. var aST = easyTemplate.aStatement;
  8. var process = function(d2){
  9. if(d2){d = d2;}
  10. return arguments.callee;
  11. };
  12. process.toString = function(){
  13. return (new Function(aST[0],aST[1]))(d);
  14. };
  15. return process;
  16. };
  17. easyTemplate.separate = function(s){
  18. var r = /\\'/g;
  19. var sRet = s.replace(/(<(\/?)#(.*?(?:\(.*?\))*)>)|(')|([\r\n\t])|(\$\{([^\}]*?)\})/g,function(a,b,c,d,e,f,g,h){
  20. if(b){return '{|}'+(c?'-':'+')+d+'{|}';}
  21. if(e){return '\\\'';}
  22. if(f){return '';}
  23. if(g){return '\'+('+h.replace(r,'\'')+')+\'';}
  24. });
  25. return sRet;
  26. };
  27. easyTemplate.parsing = function(s){
  28. var mName,vName,sTmp,aTmp,sFL,sEl,aList,aStm = ['var aRet = [];'];
  29. aList = s.split(/\{\|\}/);
  30. var r = /\s/;
  31. while(aList.length){
  32. sTmp = aList.shift();
  33. if(!sTmp){continue;}
  34. sFL = sTmp.charAt(0);
  35. if(sFL!=='+'&&sFL!=='-'){
  36. sTmp = '\''+sTmp+'\'';aStm.push('aRet.push('+sTmp+');');
  37. continue;
  38. }
  39. aTmp = sTmp.split(r);
  40. switch(aTmp[0]){
  41. case '+macro':mName = aTmp[1];vName = aTmp[2];aStm.push('aRet.push("<!--'+mName+' start--\>");');break;
  42. case '-macro':aStm.push('aRet.push("<!--'+mName+' end--\>");');break;
  43. case '+if':aTmp.splice(0,1);aStm.push('if'+aTmp.join(' ')+'{');break;
  44. case '+elseif':aTmp.splice(0,1);aStm.push('}else if'+aTmp.join(' ')+'{');break;
  45. case '-if':aStm.push('}');break;
  46. case '+else':aStm.push('}else{');break;
  47. case '+list':aStm.push('if('+aTmp[1]+'&&'+aTmp[1]+'.constructor === Array){with({i:0,l:'+aTmp[1]+'.length,'+aTmp[3]+'_index:0,'+aTmp[3]+':null}){for(i=l;i--;){'+aTmp[3]+'_index=(l-i-1);'+aTmp[3]+'='+aTmp[1]+'['+aTmp[3]+'_index];');break;
  48. case '-list':aStm.push('}}}');break;
  49. default:break;
  50. }
  51. }
  52. aStm.push('return aRet.join("");');
  53. if(!vName){aStm.unshift('var data = arguments[0];');}
  54. return [vName,aStm.join('')];
  55. };