inline templating class for javascript


/ Published in: JavaScript
Save to your folder(s)

I made this class because is was fed up with all those strings with escaped quotes with when building html into an output-string. You could also build a php-version of it.


Copy this code and paste it in your HTML
  1. var Html=function(lijst2){
  2. this.taglijst=[["a"],["b"],["i"],["u"],["br"],["img","border=0"],["table","border=0 cellpadding=0 cellspacing=0"],["td"],["tr"],["span"],["div"],["p"],["form"],["option"],["select"],["input"],["button"],["textarea"],["li"],["ol"],["ul"],["dl"],["dd"],["dt"],["sub"],["sup"],["script","language=javascript"],["xmp"],["link"],["style","type=text/css"],["frame"],["frameset"],["iframe"],["body"],["html"],["head"],["title"],["hr"],["map"],["area"],["h1"]]
  3. if(lijst2){this.taglijst=this.taglijst.concat(lijst2)}
  4. this.toevoeglijst = lijst2
  5. this.uitvoeren=function(obj,str){
  6. var u ="",param
  7. if(str){
  8. var arr=str.match(/\$\w+/g)
  9. if(arr){
  10. for(var i=0;i<arr.length;i++){
  11. param=arr[i].substr(1)
  12. try{
  13. str = str.replace(eval("/\\\$"+param+"/g"),obj(param))
  14. } catch(e){}
  15. }
  16. }
  17. return str
  18. }
  19. return ""
  20. }
  21. this.tag=function(id,a){
  22. var str = "<"+id+(a[0]?" "+a[0]:"")+">"
  23. if(!id.match(/^img|br|input$/&&!id.match(/^area$/))){str+=(a[1]||"")+"<"+"/"+id+">"}
  24. return str
  25. }
  26. this.param=[]
  27. this.addparam=function(a,ispreset){
  28. a=ispreset?a.replace(/(=)([^ ]+)?/gi,'$1"$2"'):a.replace(/(=)(.+)/gi,'$1"$2"')
  29. this.param[this.param.length]=a
  30. }
  31. this.getparam=function(){var a=this.param.join(" ");this.param=[];return a}
  32. this.read=function(args,presets){
  33. var temp,content="",key,naam,size,quot="'",temp2
  34. var re=/^\w+\s*=\s*[^<>=]+|^nowrap/
  35. for(var i=0;i<args.length;i++){
  36. args[i]=String(args[i]).replace(/\s*=\s*/g,"=")
  37. if(String(args[i]).match(re)){/*het is een parameter*/
  38. temp=args[i].split(/&&/)// was ;|&
  39. inner:for(var j=0;j<temp.length;j++){
  40. if(presets){
  41. if(presets.indexOf(naam=temp[j].match(/^\w+=/))!=-1){
  42. presets=presets.replace(eval("/"+naam+"\\w+/"),temp[j])
  43. continue inner
  44. }
  45. }
  46. this.addparam(temp[j])
  47. }
  48. }
  49. else {content+=args[i]}
  50. }
  51. if(presets){this.addparam(presets,true)}
  52. return [this.getparam(),content]
  53. }
  54. for(var i=0;i<this.taglijst.length;i++){var a=this.taglijst[i]
  55. this[a[0]]=Function("return this.tag('"+a[0]+"',this.read(arguments,'"+(a[1]||"")+"'))")
  56. }
  57. }
  58. var ClsHtml = new Html()
  59.  
  60.  
  61. // e.g.: now you could make an imagetag inside a href:
  62.  
  63. with(ClsHtml){
  64.  
  65. var output = a("class=mylink","href=http://www.example.com/",img("src=/images/myimg.jpg","width=20px"))
  66.  
  67. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.