Posted By

pablo_PXL on 02/06/11


Tagged

template html array recursion tohtml


Versions (?)

Page-like structured array to HTML


 / Published in: JavaScript
 

URL: http://www.twitter.com/pablo_PXL

All glory to the ml function.

  1. /*
  2. All glory to the ml()
  3. @subp Page-like structured array
  4. */
  5. function ml(subp,ctx){
  6. var out = '', ctx = ctx||{}, force = ['script'],
  7. clean = function(t){return t.replace(/"/g,'"')},
  8. fill = function(t){return t.replace(/{{[^}]*}}/g,
  9. function(hld){with(ctx){return (eval(hld))}})},
  10. render_tags = arguments.callee,
  11. render_props = function(props){
  12. var out = '';
  13. if (props) for(var p in props){
  14. if(props.hasOwnProperty(p))
  15. out += ' '+p+'="'+clean(props[p])+'"';
  16. } return out;
  17. };
  18.  
  19. for(var i=0,l=subp.length;i<l;i++){
  20. var len = subp[i].length;
  21. var name = subp[i][0],
  22. props = len>1&&!subp[i][1].pop?subp[i][1]:null,
  23. tags = subp[i][len-1].pop?subp[i][len-1]:null;
  24. var rtags = (!tags?null:tags.length==1?tags:render_tags(tags,ctx)),
  25. rprops = props?render_props(props):'';
  26.  
  27. out += rtags||(force.indexOf(name)>-1)?
  28. '<'+name+(rprops?rprops:'')+'>'+(rtags||'')+'</'+name+'>':
  29. '<'+name+(rprops?rprops:'')+'/>';
  30. } return fill(out);
  31. }
  32.  
  33. // Some testing
  34. var ctx = { a:1,b:2 };
  35. var page = [
  36. ['html',[
  37. ['head',[['script',{ type: 'text/javascript', src: 'http://www.pablovidal.org/js/jquery-underscore'}],
  38. ['script',{type: 'text/javascript'},['console.log($);']]]
  39. ],
  40. ['body',[['h1',['ml 0.1']],
  41. ['span',{style:'font-style:italic'},['round {{ a }}... maybe {{ b }}... fight']],['br']]
  42. ]]
  43. ]
  44. ];
  45.  
  46. document.write(ml(page,ctx));

Report this snippet  

You need to login to post a comment.