Saturday, February 26, 2011

Standalone ExtJS XTemplate classes

ExtJS XTemplates are awesome!  They provide an easy way to combine custom presentation markup with simple or complex data on the client.  Sometimes that markup needs to be more dynamic than simply plugging the data straight into the template.  But, the Ext folks already thought of that and allow you to add methods to your XTemplate definition.  This is great, but can lead to gangly template definitions with scoping issues.

In a recent situation at work we had a 400+ line template definition - only about 20 lines of that was the presentation template, the rest being methods to manipulate/interpret the data (beyond the conversions we had already applied to the data).  In our situation we needed to interpret the same piece of data in different ways depending on where we were in the template (context) as well as the type of view the user wanted to see.  For those of you familiar with XTemplates you will realize that the 400+ lines of template definition are in the constructor call to the XTemplate class - basically a huge constructor parameter.  Obviously it was time for some refactoring.

I have written numerous custom components in javascript, but never one extending the XTemplate, so I decided to try making our template a custom class that extended the ExtJS XTemplate.  Turns out it worked beautifully with very little modification to the original template (other than relocating it to its own file and doing some minor restructuring).  The template markup became part of the call to the super constructor in my new class' constructor and the methods became first class citizens of my new class (which ext accomplishes behind the scenes anyway in the original implementation).

As a result the client code using the template only needed a single line to create an instance of the template, the template is now reusable if needed, the code is cleaner all around, and the scope/context inside the template methods is more natural and easier to understand.

See also:  injecting extjs components via html templates

2 comments:

Unknown said...

Hello Russ,
can you post a sample code of this extended XTEmplate ?

Thank's

Claudio

ricardok1 said...

Hi there,

Can you share your standalone JS?

I need to use the xtemplate outside extjs environment and inside at different app locations.

Thanks
Ricardo
Portugal