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):


{#template MAIN}

shopping cart:

{#foreach $T.productItems as item}

{#include shoppingitem root=$T.item}

{#/for}
total amount: ${$T.transactionAmount}

{#if $T.transactionAmount > 0}







{#/if}

{#/template MAIN}

-----------------------------------------

{#template shoppingitem}

{#if $T.product.img != ''} {#/if}

product name : {$T.product.title}

calculation : ${$T.product.price} * {$T.quantity}

remove

{#/template shoppingitem}



USAGE :

$("#shoppingCart").setTemplateURL("shopping_cart.tpl");
$("#shoppingCart").processTemplate(ShoppingCart);


DATA :

var ShoppingCart = {
productItems : [
{ quantity:1, product : {
id :4,
title :'apple',
description :'mmmm - cool !',
sku :'0x4',
price :1,
category :'other',
img :'apple.jpg'}},

{ quantity:2, product : {
id :2,
title :'apple juice',
description :'apple juice description - bla-bla-bla',
sku :'0x2',
price :5,
category :'drink',
img :'AppleJuice.jpg'}}
],
transactionAmount : 11
};


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

No comments: