Putting ExtJS templates in separate files

To create a template in ExtJS you usually have to put the template code inline in your javascript.
That could lead to problems if you want to edit your code and the designer wants to change the template. Therefore it’s a good idea to put the template in a separate file.

For that reason I built this loader singleton that is capable of lazy loading ExtJS templates:

Then you can just use your template by calling:

If you call the template loader a second time, the template is not loaded again but retrieved from cache, so you may also preload all your templates before the application starts.

Update: You can find this code and all my other ExtJS components bundled in a library called ‘extensive’. Enjoy the code and feel free to support the project by participating.

  • I think abstracting templates from javascript code cool.

    But why not create a “constants” configuration object with your templates in them?

  • Florian Gilde

    I think its better to extend from XTemplate, for example

    Ext.define(‘My.Controls.ExternalTemplate’, {
    extend: ‘Ext.XTemplate’,
    alternateClassName: ‘My.ExternalTemplate’,

    constructor: function (htmlOrFilePath, config) {
    if (this._isFileName(htmlOrFilePath)) {
    My.ExternalTemplate.loadFromFile(htmlOrFilePath, function (tpl) {
    Ext.apply(this, Ext.merge(tpl, config));
    }, this, false);
    } else {

    statics: {
    cache: {},
    loadFromFile: function (url, callback, scope, async) {
    if (async === undefined) {
    async = true;
    if (My.ExternalTemplate.cache[url] === undefined) {
    url: url,
    async: async,
    success: function (xhr) {
    var template = new My.ExternalTemplate(xhr.responseText);
    My.ExternalTemplate.cache[url] = template;
    Ext.callback(callback, scope, [template]);
    } else {
    Ext.callback(callback, scope, [My.ExternalTemplate.cache[url]]);

    _isFileName: function (s) {
    return !s.contains(‘<');

    And you can call it with

    Ext.create('My.ExternalTemplate', 'app/templates/WindowMenuTemplate.html');