ExtJS and External Template Files

by Clint on September 22, 2011

ExtJS makes it easy to apply a template to a bunch of data (resulting in HTML output, for example). Most of the examples you’ll see show this being done with the template hard-coded as a JavaScript string. That’s fine, but what if you’d rather have your template in its own file? I recently had to do this and thought I’d share the code in case it’s helpful to anyone else.

First, here’s the usual example of a template hard-coded as a JavaScript string (click on the “Result” tab to run the code–it may take a few seconds for the output to appear):

In this case, the template is pretty small, so having it in the JavaScript isn’t too annoying. But for the sake of demonstration let’s pretend that putting in its own file makes it much easier to read/maintain. In this case, I’ve moved it to a GitHub Gist, which you can see here. To use it, we’ll modify our ExtJS code as follows:

How does this work? Every ExtJS component has the ability to remotely load and display HTML via the “loader” property, which you use to configure a Ext.ComponentLoader. The ComponentLoader lets you specify your own “renderer”–a function that handles the server response. What we’ve done is create our own “renderer” function that converts the server response–our template file–into an XTemplate. By making it a static function in our utility class, we can easily re-use it throughout the app.

This solution won’t make sense in every scenario, but if you’d prefer to keep your template in its own file and don’t mind the extra network traffic it’s a nice alternative to coding your templates as JavaScript strings.

Clint Harris is an independent software consultant living in Brooklyn, New York. He can be contacted directly at ten.sirrahtnilc@tnilc.
  • Davut Çapulcu

    Small but very nice tip, was useful for me.