2009-01-27

JavaScript and templates

Sometimes - it's necessary to build HTML code by JavaScript
one of desigion - create dirty JavaScript code - with innerHTML
another - approach - use templating

so templating for jQuery - I have used jTemplates.

Features:
- Fast*, Small (<10kB)
- 100% in JavaScript
- Work with Ajax and/or JSON
- Allow to use JavaScript code in templates
- Work with jQuery
- Allow to build cascading templates
- Allow to define parameters in templates
- Syntax similar to Smarty
- Live Refresh! - automatic update content from server
- Free to commercial or non-commercial use!

Also it allowed to using multiple templates in one file.

Example:



Template example (shopping_cart.tpl):

  1. {#template MAIN}  
  2.  <div>  
  3.   <b>shopping cart:</b>  
  4.   
  5.   {#foreach $T.productItems as item}  
  6.   <div>  
  7.   {#include shoppingitem root=$T.item}  
  8.   </div>  
  9.   {#/for}  
  10.   <span>total amount: ${$T.transactionAmount}</span>  
  11.   
  12.   {#if $T.transactionAmount > 0}  
  13.     <label class="scartLabel">tax : </label><input type="text" value="0" id="trasactionTax">  
  14.   
  15.    <label class="scartLabel">shipping : </label><input type="text" value="0" id="shipping">  
  16.   
  17.    <input type="button" value="process transaction" id="processTransaction">  
  18.   
  19.    <input type="button" value="reset shopping cart" id="resetTransaction">  
  20.   {#/if}  
  21.  </div>  
  22. {#/template MAIN}  
  23.   
  24. -----------------------------------------  
  25.   
  26. {#template shoppingitem}  
  27. <div class="scItem" align="center">  
  28. {#if $T.product.img != ''} <img src="img/{$T.product.img}"> {#/if}  
  29.   
  30. product name : {$T.product.title}  
  31.    
  32. calculation : ${$T.product.price} * {$T.quantity}  
  33.   
  34. <b class="removeItemFromSC" id="removeItemFromSC{$T.product.id}">remove</b>  
  35. </div>  
  36. {#/template shoppingitem}  


USAGE :
  1. $("#shoppingCart").setTemplateURL("shopping_cart.tpl");  
  2. $("#shoppingCart").processTemplate(ShoppingCart);  


DATA :
  1. var ShoppingCart = {  
  2.  productItems : [  
  3.   { quantity:1, product : {  
  4.     id :4,  
  5.     title :'apple',  
  6.     description :'mmmm - cool !',  
  7.     sku :'0x4',  
  8.     price :1,  
  9.     category :'other',  
  10.     img :'apple.jpg'}},  
  11.       
  12.   { quantity:2, product : {  
  13.     id :2,  
  14.     title :'apple juice',  
  15.     description :'apple juice description - bla-bla-bla',  
  16.     sku :'0x2',  
  17.     price :5,  
  18.     category :'drink',  
  19.     img :'AppleJuice.jpg'}}      
  20.  ],  
  21.  transactionAmount : 11  
  22. };  


it's easy & usable.
thx 2 tPython for plugin :)

No comments: