PDA

View Full Version : Formatting template with javascript



Limbo
12 Jul 2011, 7:30 AM
I have an itemTpl in my list and am wondering if it is possible to call javascript functions in the template. F.x. I have a number, that I would like to format somehow, maybe with Math.round(). Is this possible?

Like change this:

itemTpl: '<div class="DocList">{Number}</div>';

to:

itemTpl: '<div class="DocList">{DoSomeJavascrintThing(Number)}</div>';

Or something like this. Hope you get what I'm after :)

Is it possible? Or is the only possible to do the formatting on the server and return it correctly formatted to the datastore?

StuartAshworth
12 Jul 2011, 7:44 AM
It's definitely possible and there are a couple of ways to go about.

Using Template Member Functions
You can specify your own custom methods to attach to a template which you can execute within the template itself. You can specify these as properties of the template's final constructor parameter. For example,




var tpl = new Ext.XTemplate('{myNumber}', {
formatMyNumber: function(number){
return Math.round(number);
}
});



You can then access this function in a couple of ways:




var tpl = new Ext.XTemplate('{[this.formatMyNumber(values.myNumber)]}', {
formatMyNumber: function(number){
return Math.round(number);
}
});

// or

var tpl = new Ext.XTemplate('{myNumber:this.formatMyNumber}', {
formatMyNumber: function(number){
return Math.round(number);
}
});



Any code within the {[...]} syntax is executed in the scope of the template itself (which the new formatMyNumber method is a member of).

Use Global Functions
If your formatting code is something global then this can be executed directly in the {[..]} syntax. For example,




var tpl = new Ext.XTemplate('{[Math.round(values.myNumber)]}');




Hope this helps!

Limbo
18 Jul 2011, 7:47 AM
This worked just as I wanted. Thanks :)