PDA

View Full Version : Functions in Template



enigmatic
14 Jul 2010, 6:25 AM
What is the format for adding a reference to a function in a template? I have a model where I want to add "pretty print" functions, as well as some auto-generated data. I see in the geocongress application that you can add a function in the XTemplate itself (using {district:this.ordinal}), but I cannot figure out how to access any model functions and I don't want to rewrite the same functions every time I create a template.

evant
14 Jul 2010, 6:37 AM
What do you mean by "model" functions?

enigmatic
14 Jul 2010, 6:47 AM
What do you mean by "model" functions?

A simple example would be a percentage. I have MaxSpace and FreeSpace fields in my model. I would like a pctFree function that returned FreeSpace/MaxSpace.

I also have several numbers that I don't want to change to fixed point, but when showing them to the user, I don't want to show anything beyond the 2nd significant digit. So, using the pctFree as an example, the function would look like this:



pctFree: function() {
var maxSpace = this.get('MaxSpace');
var freeSpace = this.get('FreeSpace');

var pct = freeSpace / maxSpace;

return pct.toFixed(2);
}

evant
14 Jul 2010, 6:55 AM
Currently, it's not supported, you need to either
a) Have them on the template
b) Under Ext.util.Format

You could modify the source of the Template class to allow you to call functions in your own namespace, look at the compileTpl method where it uses "fm"

enigmatic
14 Jul 2010, 7:30 AM
Currently, it's not supported, you need to either
a) Have them on the template
b) Under Ext.util.Format

You could modify the source of the Template class to allow you to call functions in your own namespace, look at the compileTpl method where it uses "fm"


Actually, using formats would work since I could add a function to the Format and then have a single function to work on, but I can't tell how to use the Format class. Could it be a problem since I'm using templates built from textareas in my index.html?

Regardless, I checked out the examples under the XTemplate constructor (unfortunately, a rather unintuitive place for them) and discovered the inline code, which allows me to get my desired functionality with a simple:


{[Number(values.freeSpace / values.maxSpace).toFixed(2)]}

orangechicken
16 Sep 2010, 1:37 PM
Digging up this oldish thread to agree with the intention of the OP.

It would be very useful to keep Model-related logic in the Model.