Thursday, March 18, 2010

Change data format in Ext JS's Template and XTemplate

Sometimes you want to change format of the data before showing it to your users, example: Change it to upper case, add '$' for USD,... Ext JS provides a few formatters and the good thing is you can use them in Template and XTemplate easily.

Example:

new Ext.XTemplate(
'',
'
',
'Full name: {firstName} {lastName}',
'Account identifier: {accountIdentifier:capitalize}',
'Balance: {balance:usMoney}'
'
'
'
'
)

As you see, 'capitalize' will change your data to upper case, and 'usMoney' will format your data as USD. Look nice and much simple.

Now maybe you will ask yourself 'But how can I add my own formatters?'. To answer this question, all you need to know that Template and XTemplate use Ext.util.Format internally to format your data.

So now, when you know it, it's very easy to add yourself formatters. I will add stripping zero formatter and so how to use it.

+ Add stripping zero formatter

Ext.util.Format.stripZero = function(v) {
while (v.startsWith('0')) {
v = v.substr(1, v.length - 1);
}

return v;
};

+ Use it

new Ext.XTemplate(
'',
'
',
'Number: {number:stripZero}',
'
'
'
'
)

2 comments:

Burak Bekdemir said...

That was really helpful for me. I didn't know where to put my formatting function. Thanks a lot.

Unknown said...

ah yes thank you. Pretty weird the ExtJS API documentation does not tell this pretty important functionality.